checkmate/0000755000176200001440000000000013173640000012170 5ustar liggesuserscheckmate/inst/0000755000176200001440000000000013173633435013163 5ustar liggesuserscheckmate/inst/CITATION0000644000176200001440000000054213126422363014313 0ustar liggesusersbibentry( bibtype = "Article", key = "checkmate", title = "{checkmate}: Fast Argument Checks for Defensive R Programming", author = person("Michel", "Lang"), journal = "The R Journal", year = 2017L, url = "https://journal.r-project.org/archive/2017/RJ-2017-028/index.html", pages = "437--445", volume = 9L, number = 1L ) # vim: ft=r checkmate/inst/doc/0000755000176200001440000000000013173633435013730 5ustar liggesuserscheckmate/inst/doc/checkmate.R0000644000176200001440000001133413173633435016001 0ustar liggesusers## ----include=FALSE------------------------------------------------------- library(checkmate) ## ------------------------------------------------------------------------ fact <- function(n, method = "stirling") { if (length(n) != 1) stop("Argument 'n' must have length 1") if (!is.numeric(n)) stop("Argument 'n' must be numeric") if (is.na(n)) stop("Argument 'n' may not be NA") if (is.double(n)) { if (is.nan(n)) stop("Argument 'n' may not be NaN") if (is.infinite(n)) stop("Argument 'n' must be finite") if (abs(n - round(n, 0)) > sqrt(.Machine$double.eps)) stop("Argument 'n' must be an integerish value") n <- as.integer(n) } if (n < 0) stop("Argument 'n' must be >= 0") if (length(method) != 1) stop("Argument 'method' must have length 1") if (!is.character(method) || !method %in% c("stirling", "factorial")) stop("Argument 'method' must be either 'stirling' or 'factorial'") if (method == "factorial") factorial(n) else sqrt(2 * pi * n) * (n / exp(1))^n } ## ------------------------------------------------------------------------ fact <- function(n, method = "stirling") { assertCount(n) assertChoice(method, c("stirling", "factorial")) if (method == "factorial") factorial(n) else sqrt(2 * pi * n) * (n / exp(1))^n } ## ------------------------------------------------------------------------ f <- function(x) { assert( checkClass(x, "foo"), checkClass(x, "bar") ) } ## ----eval=FALSE---------------------------------------------------------- # # file: tests/test-all.R # library(testthat) # library(checkmate) # for testthat extensions # test_check("mypkg") ## ----eval=FALSE---------------------------------------------------------- # test_that("checkmate is a sweet extension for testthat", { # x = runif(100) # expect_numeric(x, len = 100, any.missing = FALSE, lower = 0, upper = 1) # # or, equivalent, using the lazy style: # qexpect(x, "N100[0,1]") # }) ## ----dev="svg",fig.width=6,fig.height=4,dependson="init",eval=requireNamespace("microbenchmark", quietly = TRUE)---- library(ggplot2) library(microbenchmark) x = TRUE r = function(x, na.ok = FALSE) { stopifnot(is.logical(x), length(x) == 1, na.ok || !is.na(x)) } cm = function(x) assertFlag(x) cmq = function(x) qassert(x, "B1") mb = microbenchmark(r(x), cm(x), cmq(x)) print(mb) autoplot(mb) ## ----dev="svg",fig.width=6,fig.height=4,eval=requireNamespace("microbenchmark", quietly = TRUE)---- x = runif(1000) r = function(x) stopifnot(is.numeric(x) && length(x) == 1000 && all(!is.na(x) & x >= 0 & x <= 1)) cm = function(x) assertNumeric(x, len = 1000, any.missing = FALSE, lower = 0, upper = 1) cmq = function(x) qassert(x, "N1000[0,1]") mb = microbenchmark(r(x), cm(x), cmq(x)) print(mb) autoplot(mb) ## ----dev="svg",fig.width=6,fig.height=4,eval=requireNamespace("microbenchmark", quietly = TRUE)---- x = sample(letters, 10000, replace = TRUE) r = function(x) stopifnot(is.character(x) && !any(is.na(x)) && all(nchar(x) > 0)) cm = function(x) assertCharacter(x, any.missing = FALSE, min.chars = 1) cmq = function(x) qassert(x, "S+[1,]") mb = microbenchmark(r(x), cm(x), cmq(x)) print(mb) autoplot(mb) ## ----dev="svg",fig.width=6,fig.height=4,eval=requireNamespace("microbenchmark", quietly = TRUE)---- N = 10000 x = data.frame(a = runif(N), b = sample(letters[1:5], N, replace = TRUE), c = sample(c(FALSE, TRUE), N, replace = TRUE)) r = function(x) is.data.frame(x) && !any(sapply(x, function(x) any(is.na(x)))) cm = function(x) testDataFrame(x, any.missing = FALSE) cmq = function(x) qtest(x, "D") mb = microbenchmark(r(x), cm(x), cmq(x)) print(mb) autoplot(mb) # checkmate tries to stop as early as possible x$a[1] = NA mb = microbenchmark(r(x), cm(x), cmq(x)) print(mb) autoplot(mb) ## ------------------------------------------------------------------------ checkSquareMatrix = function(x, mode = NULL) { # check functions must return TRUE on success # and a custom error message otherwise res = checkMatrix(x, mode = mode) if (!isTRUE(res)) return(res) if (nrow(x) != ncol(x)) return("Must be square") return(TRUE) } # a quick test: X = matrix(1:9, nrow = 3) checkSquareMatrix(X) checkSquareMatrix(X, mode = "character") checkSquareMatrix(X[1:2, ]) ## ------------------------------------------------------------------------ # For assertions: assert_square_matrix = assertSquareMatrix = makeAssertionFunction(checkSquareMatrix) print(assertSquareMatrix) # For tests: test_square_matrix = testSquareMatrix = makeTestFunction(checkSquareMatrix) print(testSquareMatrix) # For expectations: expect_square_matrix = makeExpectationFunction(checkSquareMatrix) print(expect_square_matrix) ## ------------------------------------------------------------------------ sessionInfo() checkmate/inst/doc/checkmate.Rmd0000644000176200001440000003005513162163362016316 0ustar liggesusers--- title: "Checkmate" author: "Michel Lang" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{checkmate} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r,include=FALSE} library(checkmate) ``` Ever used an R function that produced a not-very-helpful error message, just to discover after minutes of debugging that you simply passed a wrong argument? Blaming the laziness of the package author for not doing such standard checks (in a dynamically typed language such as R) is at least partially unfair, as R makes theses types of checks cumbersome and annoying. Well, that's how it was in the past. Enter checkmate. Virtually **every standard type of user error** when passing arguments into function can be caught with a simple, readable line which produces an **informative error message** in case. A substantial part of the package was written in C to **minimize any worries about execution time overhead**. ## Intro As a motivational example, consider you have a function to calculate the faculty of a natural number and the user may choose between using either the stirling approximation or R's `factorial` function (which internally uses the gamma function). Thus, you have two arguments, `n` and `method`. Argument `n` must obviously be a positive natural number and `method` must be either `"stirling"` or `"factorial"`. Here is a version of all the hoops you need to jump through to ensure that these simple requirements are met: ```{r} fact <- function(n, method = "stirling") { if (length(n) != 1) stop("Argument 'n' must have length 1") if (!is.numeric(n)) stop("Argument 'n' must be numeric") if (is.na(n)) stop("Argument 'n' may not be NA") if (is.double(n)) { if (is.nan(n)) stop("Argument 'n' may not be NaN") if (is.infinite(n)) stop("Argument 'n' must be finite") if (abs(n - round(n, 0)) > sqrt(.Machine$double.eps)) stop("Argument 'n' must be an integerish value") n <- as.integer(n) } if (n < 0) stop("Argument 'n' must be >= 0") if (length(method) != 1) stop("Argument 'method' must have length 1") if (!is.character(method) || !method %in% c("stirling", "factorial")) stop("Argument 'method' must be either 'stirling' or 'factorial'") if (method == "factorial") factorial(n) else sqrt(2 * pi * n) * (n / exp(1))^n } ``` And for comparison, here is the same function using checkmate: ```{r} fact <- function(n, method = "stirling") { assertCount(n) assertChoice(method, c("stirling", "factorial")) if (method == "factorial") factorial(n) else sqrt(2 * pi * n) * (n / exp(1))^n } ``` ## Function overview The functions can be split into four functional groups, indicated by their prefix. If prefixed with `assert`, an error is thrown if the corresponding check fails. Otherwise, the checked object is returned invisibly. There are many different coding styles out there in the wild, but most R programmers stick to either `camelBack` or `underscore_case`. Therefore, `checkmate` offers all functions in both flavors: `assert_count` is just an alias for `assertCount` but allows you to retain your favorite style. The family of functions prefixed with `test` always return the check result as logical value. Again, you can use `test_count` and `testCount` interchangeably. Functions starting with `check` return the error message as a string (or `TRUE` otherwise) and can be used if you need more control and, e.g., want to grep on the returned error message. `expect` is the last family of functions and is intended to be used with the [testthat package](https://cran.r-project.org/package=testthat). All performed checks are logged into the `testthat` reporter. Because `testthat` uses the `underscore_case`, the extension functions only come in the underscore style. All functions are categorized into objects to check on the [package help page](https://mllg.github.io/checkmate/reference/checkmate-package). ## In case you miss flexibility You can use [assert](https://mllg.github.io/checkmate/reference/assert) to perform multiple checks at once and throw an assertion if all checks fail. Here is an example where we check that x is either of class `foo` or class `bar`: ```{r} f <- function(x) { assert( checkClass(x, "foo"), checkClass(x, "bar") ) } ``` Note that `assert(, combine = "or")` and `assert(, combine = "and")` allow to control the logical combination of the specified checks, and that the former is the default. ## Argument Checks for the Lazy The following functions allow a special syntax to define argument checks using a special format specification. E.g., `qassert(x, "I+")` asserts that `x` is an integer vector with at least one element and no missing values. This very simple domain specific language covers a large variety of frequent argument checks with only a few keystrokes. You choose what you like best. * [qassert](https://mllg.github.io/checkmate/reference/qassert) * [qassertr](https://mllg.github.io/checkmate/reference/qassertr) ## checkmate as testthat extension To extend [testthat](https://cran.r-project.org/package=testthat), you need to IMPORT, DEPEND or SUGGEST on the `checkmate` package. Here is a minimal example: ```{r,eval=FALSE} # file: tests/test-all.R library(testthat) library(checkmate) # for testthat extensions test_check("mypkg") ``` Now you are all set and can use more than 30 new expectations in your tests. ```{r,eval=FALSE} test_that("checkmate is a sweet extension for testthat", { x = runif(100) expect_numeric(x, len = 100, any.missing = FALSE, lower = 0, upper = 1) # or, equivalent, using the lazy style: qexpect(x, "N100[0,1]") }) ``` ## Speed considerations In comparison with tediously writing the checks yourself in R (c.f. factorial example at the beginning of the vignette), R is sometimes a tad faster while performing checks on scalars. This seems odd at first, because checkmate is mostly written in C and should be comparably fast. Yet many of the functions in the `base` package are not regular functions, but primitives. While primitives jump directly into the C code, checkmate has to use the considerably slower `.Call` interface. As a result, it is possible to write (very simple) checks using only the base functions which, under some circumstances, slightly outperform checkmate. However, if you go one step further and wrap the custom check into a function to convenient re-use it, the performance gain is often lost (see benchmark 1). For larger objects the tide has turned because checkmate avoids many unnecessary intermediate variables. Also note that the quick/lazy implementation in `qassert`/`qtest`/`qexpect` is often a tad faster because only two arguments have to be evaluated (the object and the rule) to determine the set of checks to perform. Below you find some (probably unrepresentative) benchmark. But also note that this one here has been executed from inside `knitr` which is often the cause for outliers in the measured execution time. Better run the benchmark yourself to get unbiased results. ### Benchmark 1: Assert that `x` is a flag ```{r,dev="svg",fig.width=6,fig.height=4,dependson="init",eval=requireNamespace("microbenchmark", quietly = TRUE)} library(ggplot2) library(microbenchmark) x = TRUE r = function(x, na.ok = FALSE) { stopifnot(is.logical(x), length(x) == 1, na.ok || !is.na(x)) } cm = function(x) assertFlag(x) cmq = function(x) qassert(x, "B1") mb = microbenchmark(r(x), cm(x), cmq(x)) print(mb) autoplot(mb) ``` ### Benchmark 2: Assert that `x` is a numeric of length 1000 with no missing nor NaN values ```{r,dev="svg",fig.width=6,fig.height=4,eval=requireNamespace("microbenchmark", quietly = TRUE)} x = runif(1000) r = function(x) stopifnot(is.numeric(x) && length(x) == 1000 && all(!is.na(x) & x >= 0 & x <= 1)) cm = function(x) assertNumeric(x, len = 1000, any.missing = FALSE, lower = 0, upper = 1) cmq = function(x) qassert(x, "N1000[0,1]") mb = microbenchmark(r(x), cm(x), cmq(x)) print(mb) autoplot(mb) ``` ### Benchmark 3: Assert that `x` is a character vector with no missing values nor empty strings ```{r,dev="svg",fig.width=6,fig.height=4,eval=requireNamespace("microbenchmark", quietly = TRUE)} x = sample(letters, 10000, replace = TRUE) r = function(x) stopifnot(is.character(x) && !any(is.na(x)) && all(nchar(x) > 0)) cm = function(x) assertCharacter(x, any.missing = FALSE, min.chars = 1) cmq = function(x) qassert(x, "S+[1,]") mb = microbenchmark(r(x), cm(x), cmq(x)) print(mb) autoplot(mb) ``` ### Benchmark 4: Assert that `x` is a data frame with no missing values ```{r,dev="svg",fig.width=6,fig.height=4,eval=requireNamespace("microbenchmark", quietly = TRUE)} N = 10000 x = data.frame(a = runif(N), b = sample(letters[1:5], N, replace = TRUE), c = sample(c(FALSE, TRUE), N, replace = TRUE)) r = function(x) is.data.frame(x) && !any(sapply(x, function(x) any(is.na(x)))) cm = function(x) testDataFrame(x, any.missing = FALSE) cmq = function(x) qtest(x, "D") mb = microbenchmark(r(x), cm(x), cmq(x)) print(mb) autoplot(mb) # checkmate tries to stop as early as possible x$a[1] = NA mb = microbenchmark(r(x), cm(x), cmq(x)) print(mb) autoplot(mb) ``` ## Extending checkmate To extend checkmate a custom `check*` function has to be written. For example, to check for a square matrix one can re-use parts of checkmate and extend the check with additional functionality: ```{r} checkSquareMatrix = function(x, mode = NULL) { # check functions must return TRUE on success # and a custom error message otherwise res = checkMatrix(x, mode = mode) if (!isTRUE(res)) return(res) if (nrow(x) != ncol(x)) return("Must be square") return(TRUE) } # a quick test: X = matrix(1:9, nrow = 3) checkSquareMatrix(X) checkSquareMatrix(X, mode = "character") checkSquareMatrix(X[1:2, ]) ``` The respective counterparts to the `check`-function can be created using the constructors [makeAssertionFunction](https://mllg.github.io/checkmate/reference/makeAssertion), [makeTestFunction](https://mllg.github.io/checkmate/reference/makeTest) and [makeExpectationFunction](https://mllg.github.io/checkmate/reference/makeExpectation): ```{r} # For assertions: assert_square_matrix = assertSquareMatrix = makeAssertionFunction(checkSquareMatrix) print(assertSquareMatrix) # For tests: test_square_matrix = testSquareMatrix = makeTestFunction(checkSquareMatrix) print(testSquareMatrix) # For expectations: expect_square_matrix = makeExpectationFunction(checkSquareMatrix) print(expect_square_matrix) ``` Note that all the additional arguments `.var.name`, `add`, `info` and `label` are automatically joined with the function arguments of your custom check function. Also note that if you define these functions inside an R package, the constructors are called at build-time (thus, there is no negative impact on the runtime). ## Calling checkmate from C/C++ The package registers two functions which can be used in other packages' C/C++ code for argument checks. ```{c,eval=FALSE} SEXP qassert(SEXP x, const char *rule, const char *name); Rboolean qtest(SEXP x, const char *rule); ``` These are the counterparts to [qassert](https://mllg.github.io/checkmate/reference/qassert) and [qtest](https://mllg.github.io/checkmate/reference/qassert). Due to their simplistic interface, they perfectly suit the requirements of most type checks in C/C++. For detailed background information on the register mechanism, see the [Exporting C Code](http://r-pkgs.had.co.nz/src.html#clang) section in Hadley's Book "R Packages" or [WRE](https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Registering-native-routines). Here is a step-by-step guide to get you started: 1. Add `checkmate` to your "Imports" and "LinkingTo" sections in your DESCRIPTION file. 2. Create a stub C source file `"checkmate_stub.c"`. See example below. 3. Include the provided header file `` in each compilation unit where you want to use checkmate. ```{c,eval=FALSE} /* Example for (2), "checkmate_stub.c":*/ #include #include ``` ## Session Info For the sake of completeness, here the `sessionInfo()` for the benchmark (but remember the note before on `knitr` possibly biasing the results). ```{r} sessionInfo() ``` checkmate/inst/doc/checkmate.html0000644000176200001440000115270013173633435016550 0ustar liggesusers Checkmate

Checkmate

Michel Lang

2017-10-24

Ever used an R function that produced a not-very-helpful error message, just to discover after minutes of debugging that you simply passed a wrong argument?

Blaming the laziness of the package author for not doing such standard checks (in a dynamically typed language such as R) is at least partially unfair, as R makes theses types of checks cumbersome and annoying. Well, that’s how it was in the past.

Enter checkmate.

Virtually every standard type of user error when passing arguments into function can be caught with a simple, readable line which produces an informative error message in case. A substantial part of the package was written in C to minimize any worries about execution time overhead.

Intro

As a motivational example, consider you have a function to calculate the faculty of a natural number and the user may choose between using either the stirling approximation or R’s factorial function (which internally uses the gamma function). Thus, you have two arguments, n and method. Argument n must obviously be a positive natural number and method must be either "stirling" or "factorial". Here is a version of all the hoops you need to jump through to ensure that these simple requirements are met:

fact <- function(n, method = "stirling") {
  if (length(n) != 1)
    stop("Argument 'n' must have length 1")
  if (!is.numeric(n))
    stop("Argument 'n' must be numeric")
  if (is.na(n))
    stop("Argument 'n' may not be NA")
  if (is.double(n)) {
    if (is.nan(n))
      stop("Argument 'n' may not be NaN")
    if (is.infinite(n))
      stop("Argument 'n' must be finite")
    if (abs(n - round(n, 0)) > sqrt(.Machine$double.eps))
      stop("Argument 'n' must be an integerish value")
    n <- as.integer(n)
  }
  if (n < 0)
    stop("Argument 'n' must be >= 0")
  if (length(method) != 1)
    stop("Argument 'method' must have length 1")
  if (!is.character(method) || !method %in% c("stirling", "factorial"))
    stop("Argument 'method' must be either 'stirling' or 'factorial'")

  if (method == "factorial")
    factorial(n)
  else
    sqrt(2 * pi * n) * (n / exp(1))^n
}

And for comparison, here is the same function using checkmate:

fact <- function(n, method = "stirling") {
  assertCount(n)
  assertChoice(method, c("stirling", "factorial"))

  if (method == "factorial")
    factorial(n)
  else
    sqrt(2 * pi * n) * (n / exp(1))^n
}

Function overview

The functions can be split into four functional groups, indicated by their prefix.

If prefixed with assert, an error is thrown if the corresponding check fails. Otherwise, the checked object is returned invisibly. There are many different coding styles out there in the wild, but most R programmers stick to either camelBack or underscore_case. Therefore, checkmate offers all functions in both flavors: assert_count is just an alias for assertCount but allows you to retain your favorite style.

The family of functions prefixed with test always return the check result as logical value. Again, you can use test_count and testCount interchangeably.

Functions starting with check return the error message as a string (or TRUE otherwise) and can be used if you need more control and, e.g., want to grep on the returned error message.

expect is the last family of functions and is intended to be used with the testthat package. All performed checks are logged into the testthat reporter. Because testthat uses the underscore_case, the extension functions only come in the underscore style.

All functions are categorized into objects to check on the package help page.

In case you miss flexibility

You can use assert to perform multiple checks at once and throw an assertion if all checks fail.

Here is an example where we check that x is either of class foo or class bar:

f <- function(x) {
  assert(
    checkClass(x, "foo"),
    checkClass(x, "bar")
  )
}

Note that assert(, combine = "or") and assert(, combine = "and") allow to control the logical combination of the specified checks, and that the former is the default.

Argument Checks for the Lazy

The following functions allow a special syntax to define argument checks using a special format specification. E.g., qassert(x, "I+") asserts that x is an integer vector with at least one element and no missing values. This very simple domain specific language covers a large variety of frequent argument checks with only a few keystrokes. You choose what you like best.

checkmate as testthat extension

To extend testthat, you need to IMPORT, DEPEND or SUGGEST on the checkmate package. Here is a minimal example:

# file: tests/test-all.R
library(testthat)
library(checkmate) # for testthat extensions
test_check("mypkg")

Now you are all set and can use more than 30 new expectations in your tests.

test_that("checkmate is a sweet extension for testthat", {
  x = runif(100)
  expect_numeric(x, len = 100, any.missing = FALSE, lower = 0, upper = 1)
  # or, equivalent, using the lazy style:
  qexpect(x, "N100[0,1]")
})

Speed considerations

In comparison with tediously writing the checks yourself in R (c.f. factorial example at the beginning of the vignette), R is sometimes a tad faster while performing checks on scalars. This seems odd at first, because checkmate is mostly written in C and should be comparably fast. Yet many of the functions in the base package are not regular functions, but primitives. While primitives jump directly into the C code, checkmate has to use the considerably slower .Call interface. As a result, it is possible to write (very simple) checks using only the base functions which, under some circumstances, slightly outperform checkmate. However, if you go one step further and wrap the custom check into a function to convenient re-use it, the performance gain is often lost (see benchmark 1).

For larger objects the tide has turned because checkmate avoids many unnecessary intermediate variables. Also note that the quick/lazy implementation in qassert/qtest/qexpect is often a tad faster because only two arguments have to be evaluated (the object and the rule) to determine the set of checks to perform.

Below you find some (probably unrepresentative) benchmark. But also note that this one here has been executed from inside knitr which is often the cause for outliers in the measured execution time. Better run the benchmark yourself to get unbiased results.

Benchmark 1: Assert that x is a flag

library(ggplot2)
library(microbenchmark)

x = TRUE
r = function(x, na.ok = FALSE) { stopifnot(is.logical(x), length(x) == 1, na.ok || !is.na(x)) }
cm = function(x) assertFlag(x)
cmq = function(x) qassert(x, "B1")
mb = microbenchmark(r(x), cm(x), cmq(x))
print(mb)
## Unit: nanoseconds
##    expr  min     lq     mean median   uq     max neval cld
##    r(x) 6091 6372.0 30435.03 6564.5 6978 2330306   100   a
##   cm(x) 1455 1656.0  9239.63 1812.5 1935  646236   100   a
##  cmq(x)  880 1040.5  8152.48 1203.0 1329  640295   100   a
autoplot(mb)

Benchmark 2: Assert that x is a numeric of length 1000 with no missing nor NaN values

x = runif(1000)
r = function(x) stopifnot(is.numeric(x) && length(x) == 1000 && all(!is.na(x) & x >= 0 & x <= 1))
cm = function(x) assertNumeric(x, len = 1000, any.missing = FALSE, lower = 0, upper = 1)
cmq = function(x) qassert(x, "N1000[0,1]")
mb = microbenchmark(r(x), cm(x), cmq(x))
print(mb)
## Unit: microseconds
##    expr    min      lq     mean  median      uq      max neval cld
##    r(x) 18.118 18.7405 60.63018 19.2445 19.8155 4071.992   100   a
##   cm(x)  5.833  6.0635 15.97368  6.4515  6.7350  869.217   100   a
##  cmq(x)  5.661  5.8140 14.79382  6.1900  6.4180  853.256   100   a
autoplot(mb)

Benchmark 3: Assert that x is a character vector with no missing values nor empty strings

x = sample(letters, 10000, replace = TRUE)
r = function(x) stopifnot(is.character(x) && !any(is.na(x)) && all(nchar(x) > 0))
cm = function(x) assertCharacter(x, any.missing = FALSE, min.chars = 1)
cmq = function(x) qassert(x, "S+[1,]")
mb = microbenchmark(r(x), cm(x), cmq(x))
print(mb)
## Unit: microseconds
##    expr      min        lq       mean    median        uq      max neval
##    r(x) 1303.934 1324.3330 1422.35016 1325.7085 1383.3445 4661.874   100
##   cm(x)   36.816   37.3410   49.28407   38.0455   38.5895  860.683   100
##  cmq(x)   47.377   47.5895   59.59740   48.0755   48.4435  988.761   100
##  cld
##    b
##   a 
##   a
autoplot(mb)

Benchmark 4: Assert that x is a data frame with no missing values

N = 10000
x = data.frame(a = runif(N), b = sample(letters[1:5], N, replace = TRUE), c = sample(c(FALSE, TRUE), N, replace = TRUE))
r = function(x) is.data.frame(x) && !any(sapply(x, function(x) any(is.na(x))))
cm = function(x) testDataFrame(x, any.missing = FALSE)
cmq = function(x) qtest(x, "D")
mb = microbenchmark(r(x), cm(x), cmq(x))
print(mb)
## Unit: microseconds
##    expr    min     lq      mean  median       uq      max neval cld
##    r(x) 72.346 77.469 134.00455 97.2735 102.2095 2932.458   100   b
##   cm(x) 17.726 19.139  29.84926 20.1115  20.9190  805.182   100  a 
##  cmq(x) 13.289 13.959  22.55845 14.6280  14.9250  774.300   100  a
autoplot(mb)

# checkmate tries to stop as early as possible
x$a[1] = NA
mb = microbenchmark(r(x), cm(x), cmq(x))
print(mb)
## Unit: nanoseconds
##    expr   min      lq     mean  median      uq     max neval cld
##    r(x) 65567 66876.5 95745.68 92478.0 94265.0 1439443   100   b
##   cm(x)  4001  4276.5  5082.41  5127.5  5507.5   14245   100  a 
##  cmq(x)   750   861.5  1220.12  1075.0  1477.0    6614   100  a
autoplot(mb)

Extending checkmate

To extend checkmate a custom check* function has to be written. For example, to check for a square matrix one can re-use parts of checkmate and extend the check with additional functionality:

checkSquareMatrix = function(x, mode = NULL) {
  # check functions must return TRUE on success
  # and a custom error message otherwise
  res = checkMatrix(x, mode = mode)
  if (!isTRUE(res))
    return(res)
  if (nrow(x) != ncol(x))
    return("Must be square")
  return(TRUE)
}

# a quick test:
X = matrix(1:9, nrow = 3)
checkSquareMatrix(X)
## [1] TRUE
checkSquareMatrix(X, mode = "character")
## [1] "Must store characters"
checkSquareMatrix(X[1:2, ])
## [1] "Must be square"

The respective counterparts to the check-function can be created using the constructors makeAssertionFunction, makeTestFunction and makeExpectationFunction:

# For assertions:
assert_square_matrix = assertSquareMatrix = makeAssertionFunction(checkSquareMatrix)
print(assertSquareMatrix)
## function (x, mode = NULL, .var.name = vname(x), add = NULL) 
## {
##     res = checkSquareMatrix(x, mode)
##     makeAssertion(x, res, .var.name, add)
## }
# For tests:
test_square_matrix = testSquareMatrix = makeTestFunction(checkSquareMatrix)
print(testSquareMatrix)
## function (x, mode = NULL) 
## {
##     identical(checkSquareMatrix(x, mode), TRUE)
## }
# For expectations:
expect_square_matrix = makeExpectationFunction(checkSquareMatrix)
print(expect_square_matrix)
## function (x, mode = NULL, info = NULL, label = vname(x)) 
## {
##     res = checkSquareMatrix(x, mode)
##     makeExpectation(x, res, info, label)
## }

Note that all the additional arguments .var.name, add, info and label are automatically joined with the function arguments of your custom check function. Also note that if you define these functions inside an R package, the constructors are called at build-time (thus, there is no negative impact on the runtime).

Calling checkmate from C/C++

The package registers two functions which can be used in other packages’ C/C++ code for argument checks.

SEXP qassert(SEXP x, const char *rule, const char *name);
Rboolean qtest(SEXP x, const char *rule);

These are the counterparts to qassert and qtest. Due to their simplistic interface, they perfectly suit the requirements of most type checks in C/C++.

For detailed background information on the register mechanism, see the Exporting C Code section in Hadley’s Book “R Packages” or WRE. Here is a step-by-step guide to get you started:

  1. Add checkmate to your “Imports” and “LinkingTo” sections in your DESCRIPTION file.
  2. Create a stub C source file "checkmate_stub.c". See example below.
  3. Include the provided header file <checkmate.h> in each compilation unit where you want to use checkmate.
/* Example for (2), "checkmate_stub.c":*/
#include <checkmate.h>
#include <checkmate_stub.c>

Session Info

For the sake of completeness, here the sessionInfo() for the benchmark (but remember the note before on knitr possibly biasing the results).

sessionInfo()
## R version 3.4.2 (2017-09-28)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Arch Linux
## 
## Matrix products: default
## BLAS/LAPACK: /usr/lib/libopenblas_haswellp-r0.2.20.so
## 
## locale:
##  [1] LC_CTYPE=de_DE.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=de_DE.UTF-8        LC_COLLATE=C              
##  [5] LC_MONETARY=de_DE.UTF-8    LC_MESSAGES=de_DE.UTF-8   
##  [7] LC_PAPER=de_DE.UTF-8       LC_NAME=C                 
##  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
## [11] LC_MEASUREMENT=de_DE.UTF-8 LC_IDENTIFICATION=C       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] microbenchmark_1.4-2.1 ggplot2_2.2.1          checkmate_1.8.5       
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_0.12.13     knitr_1.17       magrittr_1.5     MASS_7.3-47     
##  [5] splines_3.4.2    munsell_0.4.3    lattice_0.20-35  colorspace_1.3-2
##  [9] rlang_0.1.2.9000 multcomp_1.4-7   stringr_1.2.0    plyr_1.8.4      
## [13] tools_3.4.2      grid_3.4.2       gtable_0.2.0     TH.data_1.0-8   
## [17] htmltools_0.3.6  survival_2.41-3  yaml_2.1.14      lazyeval_0.2.0  
## [21] rprojroot_1.2    digest_0.6.12    tibble_1.3.4     Matrix_1.2-11   
## [25] codetools_0.2-15 evaluate_0.10.1  rmarkdown_1.6    sandwich_2.4-0  
## [29] stringi_1.1.5    compiler_3.4.2   scales_0.5.0     backports_1.1.2 
## [33] mvtnorm_1.0-6    zoo_1.8-0
checkmate/inst/include/0000755000176200001440000000000013126450072014576 5ustar liggesuserscheckmate/inst/include/checkmate.h0000644000176200001440000000057012762012005016670 0ustar liggesusers#ifndef _CHECKMATE_H_ #define _CHECKMATE_H_ #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif Rboolean attribute_hidden qtest(SEXP x, const char *rule); SEXP attribute_hidden qassert(SEXP x, const char *rule, const char *name); #ifdef __cplusplus } #endif #endif checkmate/inst/include/checkmate_stub.c0000644000176200001440000000077713126450072017736 0ustar liggesusers#include "checkmate.h" Rboolean qtest(SEXP x, const char *rule) { static Rboolean(*fun)(SEXP, const char *) = NULL; if (fun == NULL) fun = (Rboolean(*)(SEXP, const char *)) R_GetCCallable("checkmate", "qtest"); return fun(x, rule); } SEXP qassert(SEXP x, const char *rule, const char *name) { static SEXP(*fun)(SEXP, const char *, const char *) = NULL; if (fun == NULL) fun = (SEXP(*)(SEXP, const char *, const char *)) R_GetCCallable("checkmate", "qassert"); return fun(x, rule, name); } checkmate/tests/0000755000176200001440000000000012762012005013333 5ustar liggesuserscheckmate/tests/testthat/0000755000176200001440000000000013167637071015213 5ustar liggesuserscheckmate/tests/testthat/test_r6.R0000644000176200001440000000214513162164374016722 0ustar liggesuserscontext("checkR6") test_that("checkR6", { skip_if_not_physically_installed("R6") expect_false(testR6(1)) expect_true("R6" %in% loadedNamespaces()) x = R6::R6Class("Bar", public = list(a = 5), private = list(b = 42), active = list(c = function() 99) )$new() y = list(a = 5, b = 42) class(y) = "Bar" z = R6::R6Class("Bar", cloneable = FALSE)$new() expect_succ_all(R6, x) expect_fail_all(R6, y) expect_true(checkR6(NULL, null.ok = TRUE)) expect_true(checkR6(x, "Bar", ordered = TRUE)) expect_true(checkR6(x, cloneable = TRUE)) expect_true(checkR6(z, cloneable = FALSE)) expect_true(checkR6(x, public = character(0))) expect_true(checkR6(x, public = "a")) expect_true(checkR6(x, public = "c")) expect_true(checkR6(x, private = "b")) expect_error(assertR6(NULL, null.ok = FALSE), "NULL") expect_error(assertR6(x, cloneable = FALSE), "cloneable") expect_error(assertR6(z, cloneable = TRUE), "cloneable") expect_error(assertR6(x, public = "b"), "public") expect_error(assertR6(x, private = "a"), "private") expect_error(assertR6(x, private = "c"), "private") }) checkmate/tests/testthat/test_checkCharacter.R0000644000176200001440000000404113125173031021247 0ustar liggesuserscontext("checkCharacter") test_that("checkCharacter", { myobj = c("a", "b") expect_succ_all(Character, myobj) myobj = 0 expect_fail_all(Character, myobj) expect_true(testCharacter(character(0))) expect_false(testCharacter(NULL)) expect_true(testCharacter("a")) expect_false(testCharacter(1)) expect_true(testCharacter(NA)) expect_true(testCharacter(NA_character_)) expect_true(testCharacter("a", min.chars = 1)) expect_false(testCharacter("a", min.chars = 2)) # treat NA_character_ as zero-length string expect_true(testCharacter(NA_character_, min.chars = 0)) expect_true(testCharacter(NA_character_, min.chars = 1)) expect_false(testCharacter(NA_character_, min.chars = 1, any.missing = FALSE)) expect_false(testCharacter(c("", NA_character_), min.chars = 1)) expect_true(testCharacter(NA, min.chars = 1)) expect_true(testCharacter(character(0), min.chars = 1)) x = c("abba", "baab") expect_true(testCharacter(x, pattern="a")) expect_true(testCharacter(x, pattern="ab")) expect_false(testCharacter(x, pattern="aa")) expect_false(testCharacter(x, pattern="^ab")) expect_true(testCharacter(x, pattern="AB", ignore.case=TRUE)) expect_true(testCharacter(x, pattern="AB", ignore.case=TRUE)) expect_false(testCharacter(x, pattern="AB", ignore.case=FALSE)) expect_false(testCharacter(x, pattern="AB", ignore.case=FALSE)) expect_true(testCharacter(x, pattern="a+")) expect_false(testCharacter(x, fixed="a+")) x = letters[1:3] expect_true(testCharacter(x, any.missing=FALSE, min.len=1L, max.len=3L)) expect_false(testCharacter(x, any.missing=FALSE, len=5)) expect_error(assertCharacter(1), "character") }) test_that("NAs are ignored for regexp matching (#106)", { expect_true(testCharacter(c("a", NA, "b"), pattern = "^[ab]$", any.missing = TRUE)) expect_false(testCharacter(c("a", NA, "b"), pattern = "^[cd]$", any.missing = TRUE)) expect_true(testCharacter(c("a", NA, "bbbabbb"), fixed = "a", any.missing = TRUE)) expect_false(testCharacter(c("a", NA, "bbbabbb"), fixed = "b", any.missing = TRUE)) }) checkmate/tests/testthat/test_qassertr.R0000644000176200001440000000426012762012005020223 0ustar liggesuserscontext("qtestr") expect_succ_all = function(x, rules) { xn = deparse(substitute(x)) expect_true(qtestr(x, rules), info = sprintf("rules: %s", paste0(rules, collapse=",")), label = xn) expect_identical(qassertr(x, rules), x, info = sprintf("rules: %s", paste0(rules, collapse=",")), label = xn) expect_expectation_successful(qexpectr(x, rules), info = sprintf("rules: %s", paste0(rules, collapse=",")), label = xn) } expect_fail_all = function(x, rules, pattern = NULL) { xn = deparse(substitute(x)) expect_false(qtestr(x, rules), info = sprintf("rules: %s", paste0(rules, collapse=",")), label = xn) expect_error(qassertr(x, rules), regex = pattern, info = sprintf("rules: %s", paste0(rules, collapse=",")), label = xn) expect_expectation_failed(qexpectr(x, rules), info = sprintf("rules: %s", paste0(rules, collapse=",")), label = xn) } test_that("qassertr / qtestr", { x = list(a = 1:10, b = rnorm(10)) expect_succ_all(x, "n+") expect_succ_all(x, "n10") expect_succ_all(x, "n>=1") expect_fail_all(x, "i+") expect_fail_all(x, "l") x = list(a = NULL, b = 10) expect_succ_all(x, "*") expect_fail_all(x, "0") expect_fail_all(x, "n") x = list(a = NULL, b = NULL) expect_succ_all(x, "0") expect_fail_all(x, "0+") x = list() expect_succ_all(x, "n+") expect_succ_all(x, "0+") x = list(1, 2) expect_fail_all(x, "S1", pattern = "string") x = list(1:10, NULL) expect_succ_all(x, c("v", "l", "0")) rules = c("v", "l") expect_fail_all(x, c("v", "l"), pattern = "One of") expect_succ_all(iris, c("f", "n")) expect_fail_all(iris, c("s", "n"), pattern = "One of") x = NULL expect_error(qassertr(x, "x"), "list or data.frame") expect_error(qtestr(x, "x"), "list or data.frame") }) test_that("qtestr / depth", { x = list(letters, 1:10, list(letters, 2:3, runif(10))) rules = c("v", "l") expect_true(qtestr(x, rules, depth = 1L)) expect_true(qtestr(x, rules, depth = 2L)) expect_true(qtestr(x, rules, depth = 3L)) x[[3]][[2]] = iris expect_true(qtestr(x, rules, depth = 1L)) expect_true(qtestr(x, c(rules, "d"), depth = 1L)) expect_false(qtestr(x, rules, depth = 2L)) expect_false(qtestr(x, rules, depth = 3L)) }) checkmate/tests/testthat/test_checkCount.R0000644000176200001440000000132312762012005020442 0ustar liggesuserscontext("checkCount") test_that("checkCount", { myobj = 1 expect_succ_all(Count, myobj) myobj = -1 expect_fail_all(Count, myobj) expect_false(testCount(integer(0))) expect_false(testCount(NULL)) expect_false(testCount(FALSE)) expect_false(testCount(TRUE)) expect_true(testCount(0L)) expect_false(testCount(0L, positive = TRUE)) expect_true(testCount(1L, positive = TRUE)) expect_true(testCount(1)) expect_true(testCount(0)) expect_false(testCount(-1)) expect_false(testCount(0.5)) expect_false(testCount(NA_integer_)) expect_true(testCount(NA, na.ok = TRUE)) expect_true(testCount(NA_integer_, na.ok = TRUE)) expect_false(testCount(1:2)) expect_error(assertCount(-1), ">= 0") }) checkmate/tests/testthat/test_checkFALSE.R0000644000176200001440000000027413007055223020212 0ustar liggesuserscontext("checkFALSE") test_that("checkFALSE", { expect_succ_all(FALSE, FALSE) expect_fail_all(FALSE, 1) expect_false(test_false(NA)) expect_true(test_false(NA, na.ok = TRUE)) }) checkmate/tests/testthat/test_AssertCollection.R0000644000176200001440000000212612762012005021633 0ustar liggesuserscontext("AssertCollection") test_that("Collection closure wors", { coll = makeAssertCollection() expect_is(coll, "AssertCollection") expect_output(print(coll), "Empty collection") expect_equal(coll$getMessages(), character(0L)) expect_true(coll$isEmpty()) coll$push("testing") expect_equal(coll$getMessages(), "testing") expect_false(coll$isEmpty()) expect_output(print(coll), "Collection of 1 assertion") coll$push("foo") expect_output(print(coll), "Collection of 2 assertions") expect_equal(coll$getMessages(), c("testing", "foo")) }) test_that("Reporter works", { coll = makeAssertCollection() expect_true(reportAssertions(coll)) coll$push("foo") coll$push("bar") expect_error(reportAssertions(coll), "foo") expect_error(reportAssertions(coll), "bar") }) test_that("asserts push to collection", { coll = makeAssertCollection() findme = "a" assertString(findme, add = coll) expect_true(coll$isEmpty()) expect_true(reportAssertions(coll)) assertNumeric(findme, add = coll) expect_false(coll$isEmpty()) expect_error(reportAssertions(coll), "findme") }) checkmate/tests/testthat/test_checkNull.R0000644000176200001440000000037212762012005020267 0ustar liggesuserscontext("checkNull") test_that("checkNull", { myobj = NULL expect_succ_all(Null, myobj) myobj = TRUE expect_fail_all(Null, myobj) expect_false(testNull(integer(0))) expect_true(testNull(NULL)) expect_error(assertNull(-1), "NULL") }) checkmate/tests/testthat/test_interoperability.R0000644000176200001440000000160312762012005021742 0ustar liggesuserscontext("Interoperability") test_that("data.table is supported", { skip_if_not_installed("data.table") library(data.table) myobj = as.data.table(iris) expect_succ_all(DataFrame, myobj) expect_true(testDataFrame(myobj, nrow = 150, min.cols = 2, any.missing = FALSE, col.names = "strict")) expect_true(testDataFrame(data.table())) }) test_that("tibble is supported", { skip_if_not_installed("tibble") library(tibble) myobj = as_tibble(iris) expect_succ_all(DataFrame, myobj) expect_true(testDataFrame(myobj, nrow = 150, min.cols = 2, any.missing = FALSE, col.names = "strict")) expect_true(testDataFrame(data_frame())) }) test_that("magrittr is supported", { skip_if_not_installed("magrittr") library(magrittr) x = runif(10) expect_identical(x %>% assert_numeric(lower = 0, upper = 1), x) expect_identical(iris %>% assert_data_frame(min.rows = 1) %>% ncol, 5L) }) checkmate/tests/testthat/test_messages.R0000644000176200001440000000042113115456105020167 0ustar liggesuserscontext("generated messages") test_that("No extra strings attached to generated error messages", { foo = function(XX) assertFlag(XX) x = try(foo(iris), silent = TRUE) expect_error(foo(iris), "^Assertion on 'XX'") expect_error(foo(iris), "not 'data.frame'\\.$") }) checkmate/tests/testthat/test_checkDataTable.R0000644000176200001440000000270313162135564021211 0ustar liggesuserscontext("checkDataTable") test_that("checkDataTable", { skip_if_not_physically_installed("data.table") expect_false(testDataTable(iris)) expect_true("data.table" %in% loadedNamespaces()) dt = data.table::as.data.table(iris) expect_succ_all("DataFrame", dt) expect_succ_all("DataTable", dt) expect_fail_all("DataTable", iris) expect_true(testDataTable(dt, min.rows = 1, ncols = 5)) expect_false(testDataTable(dt, min.rows = 1000, ncols = 5)) expect_true(testDataTable(dt, key = character(0))) expect_true(testDataTable(dt, index = character(0))) data.table::setkeyv(dt, "Species") expect_true(testDataTable(dt, key = "Species")) expect_false(testDataTable(dt, index = "Species")) dt = data.table::as.data.table(iris) data.table::setkeyv(dt, "Species", physical = FALSE) expect_false(testDataTable(dt, key = "Species")) expect_true(testDataTable(dt, index = "Species")) dt = data.table::as.data.table(iris) data.table::setkeyv(dt, c("Petal.Width", "Petal.Length"), physical = TRUE) data.table::setkeyv(dt, c("Sepal.Length", "Sepal.Width"), physical = FALSE) expect_true(testDataTable(dt, key = c("Petal.Width", "Petal.Length"), index = c("Sepal.Width", "Sepal.Length"))) expect_error(testDataTable(dt, key = 1), "string") expect_error(testDataTable(dt, index = 1), "string") expect_error(assertDataTable(dt, key = "Species"), "primary keys") expect_error(assertDataTable(dt, index = "Species"), "secondary keys") }) checkmate/tests/testthat/test_checkPOSIXct.R0000644000176200001440000000403013167637071020621 0ustar liggesuserscontext("checkPOSIXct") test_that("checkPOSIXct", { origin = "1970-01-01" now = Sys.time() yesterday = now - 24 * 60 * 60 tomorrow = now + 24 * 60 * 60 now_est = as.POSIXct(as.numeric(now), tz = "EST", origin = origin) now_gmt = as.POSIXct(as.numeric(now), tz = "GMT", origin = origin) yesterday_gmt = as.POSIXct(as.numeric(now), tz = "GMT", origin = origin) tomorrow_gmt = as.POSIXct(as.numeric(now), tz = "GMT", origin = origin) expect_succ_all(POSIXct, now, lc = "posixct", cc = "POSIXct") expect_fail_all(POSIXct, 1, lc = "posixct", cc = "POSIXct") dates = c(yesterday, now, tomorrow, NA) expect_true(testPOSIXct(dates, min.len = 1, max.len = 10)) expect_true(testPOSIXct(dates, len = 4)) expect_true(testPOSIXct(dates, unique = TRUE)) expect_true(testPOSIXct(dates, all.missing = FALSE)) expect_true(testPOSIXct(dates, sorted = TRUE)) expect_true(testPOSIXct(c(now, now), sorted = TRUE)) expect_error(assertPOSIXct(c(dates, dates), unique = TRUE)) expect_error(assertPOSIXct(dates, any.missing = FALSE), "missing") expect_error(assertPOSIXct(rev(dates), sorted = TRUE), "sorted") expect_true(testPOSIXct(dates, lower = yesterday)) expect_true(checkPOSIXct(dates, upper = tomorrow)) expect_error(assertPOSIXct(dates, lower = now), ">=") expect_error(assertPOSIXct(dates, upper = now), "<=") x = checkPOSIXct(dates, lower = now) expect_true(grepl("[0-9]{4}-[0-9]{2}-[0-9]{2}", x)) x = checkPOSIXct(dates, upper = now) expect_true(grepl("[0-9]{4}-[0-9]{2}-[0-9]{2}", x)) # timezone checks expect_error(assertPOSIXct(now_est, lower = yesterday), "Timezones") expect_error(assertPOSIXct(now_est, upper = tomorrow), "Timezones") expect_error(assertPOSIXct(now, lower = yesterday_gmt), "Timezones") expect_error(assertPOSIXct(now, upper = tomorrow_gmt), "Timezones") expect_error(assertPOSIXct(now_est, lower = yesterday_gmt), "Timezones") expect_error(assertPOSIXct(now_est, upper = tomorrow_gmt), "Timezones") expect_true(testPOSIXct(now_gmt, lower = yesterday_gmt, upper = tomorrow_gmt)) }) checkmate/tests/testthat/test_checkSubset.R0000644000176200001440000000257713167073256020652 0ustar liggesuserscontext("checkSubset") test_that("checkSubset", { myobj = letters[1:3] expect_succ_all(Subset, myobj, letters) myobj = 1:2 expect_fail_all(Subset, myobj, letters) expect_false(testSubset(character(0), letters, empty.ok = FALSE)) expect_true(testSubset(character(0), letters, empty.ok = TRUE)) expect_false(testSubset(NULL, letters, empty.ok = FALSE)) expect_true(testSubset(character(0), letters, empty.ok = TRUE)) expect_false(testSubset(NULL, letters, empty.ok = FALSE)) expect_true(testSubset(NULL, letters, empty.ok = TRUE)) expect_false(testSubset(factor("a"), letters)) expect_true(testSubset(1., 1:2)) expect_true(testSubset(factor("a"), factor(letters))) expect_true(testSubset(1L, 1:10)) expect_true(testSubset(3:4, 1:10)) expect_false(testSubset("ab", letters)) expect_false(testSubset(NA_integer_, 1:10)) expect_error(assertSubset(-1, 1:2), "subset of") expect_error(assertSubset(1L, list()), "atomic") # issue #109 expect_true(testSubset(character(0), character(0))) expect_true(testSubset(integer(0), character(0))) expect_error(assertSubset(1, integer(0)), "empty set") }) test_that("checkSubset / fastmatch", { x = "c" y = letters[1:5] res = testSubset(x, y) expect_true(res) expect_null(attr(y, ".match.hash")) res = testSubset(x, y, fmatch = TRUE) expect_true(res) expect_class(attr(y, ".match.hash"), "match.hash") }) checkmate/tests/testthat/test_anyNaN.R0000644000176200001440000000126312762012005017543 0ustar liggesuserscontext("anyNaN") test_that("anyNaN", { xb = logical(10) xi = integer(10) xd = double(10) xc = complex(10) xl = as.list(1:10) xm = matrix(1:9, 3) xf = data.frame(a=1:5, b=1:5) expect_false(anyNaN(NULL)) expect_false(anyNaN(mean)) expect_false(anyNaN(double(0))) expect_false(anyNaN(xb)) expect_false(anyNaN(xi)) expect_false(anyNaN(xd)) expect_false(anyNaN(xc)) expect_false(anyNaN(xl)) expect_false(anyNaN(xm)) expect_false(anyNaN(xf)) xd[5] = xc[5] = xf$b[3] = NaN xl[5] = NaN expect_true(anyNaN(xd)) expect_true(anyNaN(xc)) expect_true(anyNaN(xl)) expect_true(anyNaN(xf)) x = list(1, list(1, list(1, NaN))) expect_true(anyNaN(x)) }) checkmate/tests/testthat/test_checkScalarNA.R0000644000176200001440000000057012762012005021001 0ustar liggesuserscontext("checkScalarNA") test_that("checkScalarNA", { expect_succ_all("ScalarNA", NA) expect_fail_all("ScalarNA", 1) expect_true(testScalarNA(NA_real_)) expect_false(testScalarNA(1)) expect_false(testScalarNA(rep(NA_character_, 2))) expect_expectation_successful(expect_scalar_na(NA), label = NULL) expect_error(assertScalarNA(integer(0)), "missing value") }) checkmate/tests/testthat/test_checkFilesystem.R0000644000176200001440000000526013032416073021506 0ustar liggesuserscontext("checkFile") td = tempfile("checkFile") dir.create(td, recursive=TRUE) fn = file.path(td, "myfile.ext") dn = file.path(td, "dir") ff = file.path(td, "xxx") file.create(fn) dir.create(dn) test_that("checkFile", { myobj = fn expect_succ_all(FileExists, myobj) myobj = ff expect_fail_all(FileExists, myobj) expect_false(testFileExists(character(0))) expect_false(testFileExists(NULL)) expect_false(testFileExists(dn)) expect_error(assertFileExists(character(0)), "provided") expect_error(assertFileExists(ff), "exist") expect_error(assertFileExists(dn)) expect_succ_all(FileExists, fn, extension = "ext") expect_succ_all(FileExists, fn, extension = c("foo", "ext")) expect_fail_all(FileExists, fn, extension = "foo") }) test_that("check_directory", { myobj = dn expect_succ_all(DirectoryExists, myobj) myobj = ff expect_fail_all(DirectoryExists, myobj) expect_false(testDirectoryExists(character(0))) expect_false(testDirectoryExists(fn)) expect_error(assertDirectoryExists(character(0)), "provided") expect_error(assertDirectoryExists(ff), "exist") expect_error(assertDirectoryExists(fn)) }) test_that("check_access", { myobj = R.home() expect_succ_all(Access, myobj, "r") if (.Platform$OS.type != "windows") { Sys.chmod(fn, "0000") expect_true(testAccess(fn, "")) expect_false(testAccess(fn, "x")) if (Sys.info()["user"] == "root") { expect_true(testAccess(fn, "r")) expect_true(testAccess(fn, "w")) } else { expect_false(testAccess(fn, "r")) expect_false(testAccess(fn, "w")) } Sys.chmod(fn, "0700") expect_true(testAccess(fn, "")) expect_true(testAccess(fn, "r")) expect_true(testAccess(fn, "w")) expect_true(testAccess(fn, "x")) Sys.chmod(fn, "0600") expect_true(testAccess(fn, "")) expect_true(testAccess(fn, "r")) expect_true(testAccess(fn, "rw")) expect_false(testAccess(fn, "rx")) expect_false(testAccess(fn, "wx")) expect_error(testAccess(fn, "a")) expect_error(testAccess(fn, "rrr")) } }) test_that("check_path_for_output", { myobj = ff expect_succ_all(PathForOutput, myobj) myobj = fn expect_fail_all(PathForOutput, myobj) expect_false(testPathForOutput(character(0))) expect_false(testPathForOutput(NULL)) expect_error(assertPathForOutput(character(0)), "path provided") expect_identical(assertPathForOutput(c("a", "b")), c("a", "b")) expect_identical(assertPathForOutput(ff), ff) expect_error(assertPathForOutput(fn), "exist") expect_identical(assertPathForOutput(fn, overwrite = TRUE), fn) expect_true(testPathForOutput(c(fn, ff, dn), overwrite = TRUE)) expect_false(testPathForOutput(c(fn, ff, dn), overwrite = FALSE)) }) checkmate/tests/testthat/test_checkNames.R0000644000176200001440000001006513154206633020430 0ustar liggesuserscontext("checkNames") test_that("checkNames", { nn = letters[1:3] expect_succ_all(Names, nn) expect_fail_all(Names, nn, type = "unnamed") expect_true(testNames(character(0))) expect_false(testNames(NULL)) expect_false(testNames(integer(0))) x = c("a", ".a") expect_true(testNames(x)) expect_true(testNames(x, "unique")) expect_true(testNames(x, "strict")) expect_false(testNames(1)) expect_false(testNames(NA_character_)) expect_false(testNames(NA_integer_)) expect_false(testNames("")) x = c("a", "a") expect_true(testNames(x)) expect_false(testNames(x, "unique")) expect_true(testNames("x", type = "strict")) expect_true(testNames("..x", type = "strict")) expect_true(testNames("x_1", type = "strict")) expect_true(testNames("x.", type = "strict")) expect_false(testNames("1", type = "strict")) expect_false(testNames(".1", type = "strict")) expect_false(testNames("..1", type = "strict")) expect_false(testNames("x ", type = "strict")) expect_false(testNames("ä", type = "strict")) expect_error(assertNames(c("a", "a"), "unique"), "unique") x = c("a", "1") expect_error(assertNames(x, "strict"), "naming conventions") }) test_that("argument 'type' is checked", { expect_error(checkNames("x", type = 1), "string") expect_error(checkNames("x", type = NA_character_), "missing") }) test_that("checkNames / subset.of", { x = 1:3 names(x) = letters[1:3] expect_true(testNames(names(x), subset.of = letters[1:3])) expect_true(testNames(names(x), subset.of = letters[3:1])) expect_true(testNames(names(x), subset.of = letters)) expect_false(testNames(names(x), subset.of = letters[1:2])) expect_false(testNames(names(x), subset.of = character(0))) expect_false(testNames(NULL, subset.of = character(0))) expect_true(testNames(character(0), subset.of = character(0))) expect_true(testNames(character(0), subset.of = NULL)) }) test_that("checkNames / identical.to", { x = 1:3 names(x) = letters[1:3] expect_true(testNames(names(x), identical.to = letters[1:3])) expect_false(testNames(names(x), identical.to = letters[3:1])) expect_false(testNames(names(x), identical.to = letters)) expect_false(testNames(names(x), identical.to = letters[1:2])) expect_false(testNames(names(x), identical.to = character(0))) expect_false(testNames(NULL, identical.to = character(0))) expect_true(testNames(character(0), identical.to = character(0))) expect_true(testNames(character(0), identical.to = NULL)) expect_false(testNames(NULL, identical.to = NULL)) }) test_that("checkNames / permutation.of", { x = 1:3 names(x) = letters[1:3] expect_true(testNames(names(x), permutation.of = letters[1:3])) expect_true(testNames(names(x), permutation.of = letters[3:1])) expect_false(testNames(names(x), permutation.of = letters)) expect_false(testNames(names(x), permutation.of = letters[1:2])) expect_false(testNames(names(x), permutation.of = character(0))) expect_false(testNames(NULL, permutation.of = character(0))) expect_true(testNames(character(0), permutation.of = character(0))) expect_true(testNames(character(0), permutation.of = NULL)) expect_false(testNames(NULL, permutation.of = NULL)) }) test_that("checkNames / must.include", { x = 1:3 names(x) = letters[1:3] expect_true(testNames(names(x), must.include = "a")) expect_true(testNames(names(x), must.include = letters[3:1])) expect_false(testNames(names(x), must.include = letters)) expect_true(testNames(names(x), must.include = character(0))) expect_false(testNames(NULL, must.include = character(0))) expect_true(testNames(character(0), must.include = character(0))) expect_true(testNames(character(0), must.include = NULL)) }) test_that("checkNames / errors are useful", { foo = matrix(1:9) expect_error( assertNames(colnames(foo), permutation.of = letters), "colnames\\(foo\\)" ) expect_error( assertNames(rownames(foo), permutation.of = letters), "rownames\\(foo\\)" ) }) test_that("checkNames / NULL (#120)", { expect_true(testNames(NULL, type = "unnamed")) expect_false(testNames(NULL, type = "named")) }) checkmate/tests/testthat/test_checkScalar.R0000644000176200001440000000076112762012005020564 0ustar liggesuserscontext("checkScalar") test_that("checkScalar", { myobj = "a" expect_succ_all(Scalar, myobj) myobj = 1:2 expect_fail_all(Scalar, myobj) expect_true(testScalar(TRUE)) expect_true(testScalar(1L)) expect_true(testScalar(1)) expect_true(testScalar(1+1i)) expect_false(testScalar(list(1))) expect_false(testScalar(NA, na.ok = FALSE)) expect_true(testScalar(NA, na.ok = TRUE)) expect_error(assertScalar(integer(0)), "length 1") expect_error(assertScalar(iris), "scalar") }) checkmate/tests/testthat/test_checkString.R0000644000176200001440000000227613125173027020636 0ustar liggesuserscontext("checkString") test_that("checkString", { expect_succ_all(String, "a") expect_succ_all(String, "") expect_fail_all(String, "", min.chars = 1) expect_fail_all(String, 1L) expect_succ_all(String, NA_character_, na.ok = TRUE, min.chars = 99) expect_succ_all(String, "xxxfooxxx", pattern = "foo") expect_succ_all(String, "xxxfooxxx", fixed = "foo") expect_fail_all(String, "xxxfooxxx", pattern = "bar") expect_fail_all(String, "xxxfooxxx", fixed = "bar") expect_succ_all(String, "xxxfooxxx", pattern = "FOO", ignore.case = TRUE) expect_fail_all(String, "xxxfooxxx", fixed = "FOO", ignore.case = FALSE) expect_false(testString(character(0))) expect_false(testString(NULL)) expect_true(testString("")) expect_true(testString("foo")) expect_true(testString(NA, na.ok = TRUE)) expect_false(testString(NA_character_)) expect_true(testString(NA_character_, na.ok = TRUE)) expect_true(testString(NA, na.ok = TRUE)) expect_true(testString("a", min.chars = 1)) expect_false(testString("", min.chars = 1)) expect_true(testString(NA_character_, min.chars = 1, na.ok = TRUE)) expect_true(testString(NA_real_, min.chars = 1, na.ok = TRUE)) expect_error(assertString(1)) }) checkmate/tests/testthat/test_matchArg.R0000644000176200001440000000121312762012005020100 0ustar liggesuserscontext("matchArg") test_that("matchArg", { x = c("pearson", "kendall", "spearman") choices = x expect_equal(matchArg(x, choices), choices[1]) expect_equal(matchArg(x, choices, several.ok = TRUE), choices) x = substr(x, 1, 1) expect_equal(matchArg(x[2], choices, several.ok = FALSE), choices[2]) expect_equal(matchArg(x[c(1, 3)], choices, several.ok = TRUE), choices[c(1, 3)]) expect_error(matchArg(1, 1:10), "character") expect_error(matchArg(1, letters), "character") expect_error(matchArg(letters, 1:10), "character") expect_error(matchArg(x[1:2], choices), "length") expect_error(matchArg(x[0], choices), "length 0") }) checkmate/tests/testthat/test_checkComplex.R0000644000176200001440000000121212762012005020756 0ustar liggesuserscontext("checkComplex") test_that("checkComplex", { myobj = 1+1i expect_succ_all(Complex, myobj) myobj = 1 expect_fail_all(Complex, myobj) expect_true(testComplex(complex(0L))) expect_false(testComplex(NULL)) expect_false(testComplex(TRUE)) expect_true(testComplex(NA)) expect_false(testComplex(NA, any.missing = FALSE)) expect_false(testComplex(NA, all.missing = FALSE)) expect_true(testComplex(NA_complex_)) expect_true(testComplex(1+1i)) expect_true(testComplex(as.complex(Inf))) expect_true(testComplex(c(1+1i, 2+1i), any.missing = FALSE, min.len = 1L, max.len = 3L)) expect_error(assertComplex(1), "complex") }) checkmate/tests/testthat/test_makeFunction.R0000644000176200001440000000212112762012005020774 0ustar liggesuserscontext("makeXFunction") test_that("makeAssertion", { x = assertFlag y = makeAssertionFunction(checkFlag, c.fun = "c_check_flag") expect_identical(formals(x), formals(y)) expect_equal(body(x), body(y)) x = assertList y = makeAssertionFunction(checkList) expect_identical(formals(x), formals(y)) expect_equal(body(x), body(y)) }) test_that("makeTest", { x = testFlag y = makeTestFunction(checkFlag, c.fun = "c_check_flag") expect_identical(formals(x), formals(y)) expect_equal(body(x), body(y)) x = testList y = makeTestFunction(checkList) expect_identical(formals(x), formals(y)) expect_equal(body(x), body(y)) x = testFlag y = function(x) makeTest(checkFlag(x)) expect_equal(x(TRUE), y(TRUE)) expect_equal(x(FALSE), y(FALSE)) }) test_that("makeExpectation", { x = expect_flag y = makeExpectationFunction(checkFlag, c.fun = "c_check_flag") expect_identical(formals(x), formals(y)) expect_equal(body(x), body(y)) x = expect_list y = makeExpectationFunction(checkList) expect_identical(formals(x), formals(y)) expect_equal(body(x), body(y)) }) checkmate/tests/testthat/test_include.R0000644000176200001440000000064613130632044020007 0ustar liggesuserscontext("registered c functions") test_that("include of registered C functions works", { skip_on_cran() skip_on_travis() devtools::install_github("mllg/checkmate-test-include") library(checkmate.test.include) expect_true(reexported_qtest(1, "N1")) expect_false(reexported_qtest(1, "b")) x = pi expect_identical(reexported_qassert(x, "N1"), x) expect_error(reexported_qassert(x, "b", "foo"), "foo") }) checkmate/tests/testthat/test_checkNumeric.R0000644000176200001440000000506413167637071021002 0ustar liggesuserscontext("checkNumeric") test_that("checkNumeric", { myobj = 1 expect_succ_all(Numeric, myobj) myobj = "a" expect_fail_all(Numeric, myobj) expect_true(testNumeric(integer(0))) expect_false(testNumeric(NULL)) expect_false(testNumeric(TRUE)) expect_false(testNumeric(FALSE)) expect_true(testNumeric(NA_character_)) expect_true(testNumeric(NA_real_)) expect_true(testNumeric(NaN)) expect_false(testNumeric(NA_real_, any.missing = FALSE)) expect_false(testNumeric(NA_real_, all.missing = FALSE)) expect_false(testNumeric(NaN, any.missing = FALSE)) expect_false(testNumeric(NaN, all.missing = FALSE)) expect_true(testNumeric(1L)) expect_true(testNumeric(1)) expect_true(testNumeric(Inf)) expect_true(testNumeric(-Inf)) expect_identical(assertNumeric(1:2, finite = TRUE), 1:2) expect_error(assertNumeric(c(1, Inf), finite = TRUE), "finite") expect_error(assertNumeric(c(1, -Inf), finite = TRUE), "finite") expect_true(testNumeric(1:3, any.missing=FALSE, min.len=1L, max.len=3L)) expect_false(testNumeric(1:3, any.missing=FALSE, len=5)) expect_true(testNumeric(1:3, lower = 1L, upper = 3L)) expect_false(testNumeric(1:3, lower = 5)) expect_error(assertNumeric("a"), "numeric") }) test_that("bounds are checked", { expect_error(checkNumeric(1, lower = "a"), "number") expect_error(checkNumeric(1, lower = 1:2), "length") expect_error(checkNumeric(1, lower = NA_real_), "missing") expect_error(checkNumeric(1, upper = "a"), "number") expect_error(checkNumeric(1, upper = 1:2), "length") expect_error(checkNumeric(1, upper = NA_real_), "missing") }) test_that("bounds of vectors with only missings are not checked", { expect_true(checkNumeric(NA, lower = 1)) expect_true(checkNumeric(NA_character_, upper = 10)) expect_fail_all(Numeric, 0:5, lower = 1L) expect_fail_all(Numeric, 5:15, upper = 10L) }) test_that("sorted works", { xu = runif(10) while(!is.unsorted(xu)) xu = runif(10) xs = sort(xu) expect_true(checkNumeric(xs, sorted = TRUE)) expect_true(grepl("sorted", checkNumeric(xu, sorted = TRUE), fixed = TRUE)) expect_true(checkNumeric(1., sorted = TRUE)) expect_true(checkNumeric(double(0), sorted = TRUE)) expect_true(checkNumeric(NA_real_, sorted = TRUE)) expect_true(checkInteger(rep(NA_real_, 10), sorted = TRUE)) for (i in 1:10) { x = sample(10) x[sample(10, sample(7:9, 1))] = NA if (is.unsorted(na.omit(x))) expect_true(grepl("sorted", checkNumeric(xu, sorted = TRUE), fixed = TRUE)) else expect_true(grepl("sorted", checkNumeric(xu, sorted = TRUE), fixed = TRUE)) } }) checkmate/tests/testthat/test_wf.R0000644000176200001440000000166213155455641017014 0ustar liggesuserscontext("wf / wl") test_that("wf / wl", { x = c(FALSE, TRUE, FALSE, TRUE) expect_equal(wf(x), 2L) expect_equal(wl(x), 4L) x = c(NA, TRUE, NA, TRUE, NA) expect_equal(wf(x), 2L) expect_equal(wl(x), 4L) x = logical(0L) expect_equal(wf(x), integer(0L)) expect_equal(wl(x), integer(0L)) expect_equal(wf(x), integer(0L)) expect_equal(wl(x), integer(0L)) x = c(NA, NA) expect_equal(wf(x), integer(0L)) expect_equal(wl(x), integer(0L)) x = setNames(c(NA, FALSE, TRUE, FALSE, TRUE, FALSE, NA), letters[1:7]) expect_identical(wf(x, TRUE), setNames(3L, "c")) expect_identical(wf(x, FALSE), 3L) expect_identical(wl(x), setNames(5L, "e")) expect_identical(wl(x, FALSE), 5L) expect_equal(wf(logical(0)), integer(0)) expect_equal(wl(logical(0)), integer(0)) expect_error(wf(42), "logical") expect_error(wl(42), "logical") expect_error(wf(NA, iris), "use.names") expect_error(wl(NA, iris), "use.names") }) checkmate/tests/testthat/test_checkInteger.R0000644000176200001440000000341313064452167020766 0ustar liggesuserscontext("checkInteger") test_that("checkInteger", { myobj = 1L expect_succ_all(Integer, myobj) myobj = 1 expect_fail_all(Integer, myobj) expect_true(testInteger(integer(0))) expect_false(testInteger(NULL)) expect_false(testInteger(TRUE)) expect_false(testInteger(FALSE)) expect_true(testInteger(NA)) expect_false(testInteger(NA, any.missing = FALSE)) expect_false(testInteger(NA, all.missing = FALSE)) expect_true(testInteger(1L)) expect_true(testInteger(1:3, any.missing = FALSE, min.len = 1L, max.len = 3L)) expect_false(testInteger(1:3, any.missing = FALSE, len = 5)) expect_true(testInteger(1:3, lower = 1L, upper = 3L)) expect_false(testInteger(1:3, lower = 5)) expect_false(testInteger(1:3, upper = 1)) expect_error(assertInteger(1), "integer") }) test_that("bounds of vectors with only missings are not checked", { expect_true(checkInteger(NA, lower = 1)) expect_true(checkInteger(NA_character_, upper = 10)) expect_fail_all(Integer, 0L, lower = 1L) expect_fail_all(Integer, 100L, upper = 10L) }) test_that("sorted works", { xu = sample(10) while(!is.unsorted(xu)) xu = sample(10) xs = sort(xu) expect_true(checkInteger(xs, sorted = TRUE)) expect_true(grepl("sorted", checkInteger(xu, sorted = TRUE), fixed = TRUE)) expect_true(checkInteger(1L, sorted = TRUE)) expect_true(checkInteger(integer(0), sorted = TRUE)) expect_true(checkInteger(NA_integer_, sorted = TRUE)) expect_true(checkInteger(rep(NA_integer_, 10), sorted = TRUE)) for (i in 1:10) { x = sample(10) x[sample(10, sample(7:9, 1))] = NA if (is.unsorted(na.omit(x))) expect_true(grepl("sorted", checkInteger(xu, sorted = TRUE), fixed = TRUE)) else expect_true(grepl("sorted", checkInteger(xu, sorted = TRUE), fixed = TRUE)) } }) checkmate/tests/testthat/test_checkMatrix.R0000644000176200001440000000632413156440203020627 0ustar liggesuserscontext("checkMatrix") test_that("checkMatrix", { myobj = matrix(1:9, 3) expect_succ_all(Matrix, myobj) myobj = TRUE expect_fail_all(Matrix, myobj) x = matrix(1:9, 3) expect_true(testMatrix(x)) expect_true(testMatrix(matrix(nrow=0, ncol=0))) expect_false(testMatrix(NULL)) x[2,2] = NA expect_true(testMatrix(x)) expect_false(testMatrix(x, any.missing = FALSE)) xl = matrix(TRUE) xi = matrix(1L) xr = matrix(1.) xs = matrix("a") xc = matrix(1+1i) xx = array(list(1, 1), dim = c(1, 2)) xe = matrix(nrow = 0, ncol = 0); storage.mode(xe) = "double" expect_true(testMatrix(xl, "logical")) expect_true(testMatrix(xi, "integer")) expect_true(testMatrix(xr, "double")) expect_true(testMatrix(xe, "double")) expect_true(testMatrix(xr, "numeric")) expect_true(testMatrix(xc, "complex")) expect_true(testMatrix(xs, "character")) expect_true(testMatrix(xx, "list")) expect_false(testMatrix(xs, "logical")) expect_false(testMatrix(xs, "integer")) expect_false(testMatrix(xs, "double")) expect_false(testMatrix(xe, "logical")) expect_false(testMatrix(xs, "numeric")) expect_false(testMatrix(xs, "complex")) expect_false(testMatrix(xl, "character")) expect_false(testMatrix(xx, "numeric")) expect_false(testMatrix(xx, "atomic")) expect_true(testMatrix(xi, "integerish")) expect_true(testMatrix(xr, "integerish")) expect_false(testMatrix(xi+0.1, "integerish")) expect_true(testMatrix(x, min.rows = 1, min.cols = 1)) expect_true(testMatrix(x, nrows = 3, ncols = 3)) expect_true(testMatrix(xx, nrows = 1, ncols = 2)) expect_true(testMatrix(xe, nrows = 0, ncols = 0)) expect_false(testMatrix(x, min.rows = 5)) expect_false(testMatrix(x, min.cols = 5)) expect_false(testMatrix(x, nrows = 5)) expect_false(testMatrix(x, ncols = 5)) expect_false(testMatrix(x, row.names = "named")) expect_false(testMatrix(x, col.names = "named")) rownames(x) = letters[1:3]; colnames(x) = NULL expect_true(testMatrix(x, row.names = "named")) expect_false(testMatrix(x, col.names = "named")) colnames(x) = letters[1:3]; rownames(x) = NULL expect_false(testMatrix(x, row.names = "named")) expect_true(testMatrix(x, col.names = "named")) colnames(x) = rownames(x) = letters[1:3] expect_true(testMatrix(x, row.names = "named")) expect_true(testMatrix(x, col.names = "named")) # named and unnamed is the same for "empty" matricies expect_true(testMatrix(xe, row.names = "unnamed")) expect_true(testMatrix(xe, col.names = "unnamed")) expect_true(testMatrix(xe, row.names = "strict")) expect_true(testMatrix(xe, col.names = "strict")) expect_error(assertMatrix(iris), "matrix") expect_error(assertMatrix(matrix(), min.rows = 99), "99") }) test_that("dimension arguments are checked", { x = matrix(1) expect_error(checkMatrix(x, min.rows = 1.2), "close") expect_error(checkMatrix(x, min.rows = NA_integer_), "missing") expect_error(checkMatrix(x, min.rows = -1), ">= 0") }) test_that("dimensions are reported correctly", { x = matrix(1:42, ncol = 1) expect_true(grepl(42, checkMatrix(x, nrows = 43))) expect_true(grepl(42, checkMatrix(x, min.rows = 43))) x = t(x) expect_true(grepl(42, checkMatrix(x, ncols = 43))) expect_true(grepl(42, checkMatrix(x, min.cols = 43))) }) checkmate/tests/testthat/test_qassert.R0000644000176200001440000001773712763531222020066 0ustar liggesuserscontext("qtest") xb = logical(10); xb[5] = NA xi = integer(10); xi[5] = NA xr = double(10); xr[5] = NA xc = complex(10); xc[5] = NA xl = as.list(1:10); xl[5] = list(NULL) xm = matrix(1:9, 3); xm[2, 3] = NA xd = data.frame(a=1:5, b=1:5); xd$b[3] = NA xf = factor(letters[1:10]); xf[5] = NA xe = new.env(); xe$foo = 1 expect_succ_all = function(x, rules) { xn = deparse(substitute(x)) expect_true(qtest(x, rules), info = sprintf("rules: %s", paste(rules, collapse=",")), label = xn) expect_identical(qassert(x, rules), x, info = sprintf("rules: %s", paste(rules, collapse=",")), label = xn) expect_expectation_successful(qexpect(x, rules), info = sprintf("rules: %s", paste(rules, collapse=",")), label = xn) } expect_fail_all = function(x, rules, pattern = NULL) { xn = deparse(substitute(x)) expect_false(qtest(x, rules), info = sprintf("rules: %s", paste0(rules, collapse=",")), label = xn) expect_error(qassert(x, rules), regex = pattern, info = sprintf("rules: %s", paste0(rules, collapse=",")), label = xn) expect_expectation_failed(qexpect(x, rules), info = sprintf("rules: %s", paste0(rules, collapse=",")), label = xn) } test_that("type and missingness", { expect_succ_all(xb, "b") expect_fail_all(xb, "B") expect_succ_all(xi, "i") expect_fail_all(xi, "I") expect_succ_all(xr, "r") expect_fail_all(xr, "R") expect_succ_all(xc, "c") expect_fail_all(xc, "C") expect_succ_all(xl, "l") expect_fail_all(xl, "L") expect_succ_all(xm, "m") expect_fail_all(xm, "M") expect_succ_all(xd, "d") expect_fail_all(xd, "D") expect_succ_all(xe, "e") expect_succ_all(xf, "f") expect_fail_all(xf, "F") expect_fail_all(xd, "b") expect_fail_all(xd, "i") expect_fail_all(xd, "r") expect_fail_all(xd, "c") expect_fail_all(xd, "l") expect_fail_all(xd, "m") expect_fail_all(xl, "e") expect_fail_all(xm, "r") expect_fail_all(xl, "d") expect_fail_all(xl, "f") expect_fail_all(xl, c("f", "n"), "One of") expect_error(qassert(1, "O"), "Unknown class identifier") }) test_that("integerish", { expect_succ_all(xb, "x") expect_succ_all(xi, "x") expect_succ_all(xi, "x") expect_fail_all(xi, "X") expect_succ_all(xr, "x") expect_fail_all(xr, "X") expect_fail_all(1:3+.0001, "x") expect_fail_all(xd, "x") }) test_that("length", { expect_succ_all(xb, "b+") expect_succ_all(xb, "b10") expect_succ_all(logical(1), "b+") expect_succ_all(logical(1), "b?") expect_succ_all(logical(1), "b1") expect_fail_all(xb, "b?") expect_fail_all(xb, "b5") expect_fail_all(xb, "b>=50") expect_succ_all(xb, "b<=50") expect_succ_all(xe, "e1") expect_fail_all(xe, "e>=2") expect_fail_all(xe, "f+") expect_error(qassert(1, "n9999999999999"), "handle length") expect_error(qassert(1, "n-1"), "negative length") }) test_that("bounds", { xx = 1:3 expect_succ_all(xx, "i+(0,4)") expect_succ_all(xx, "i+(0.9999,3.0001)") expect_succ_all(xx, "i+(0,1e2)") expect_succ_all(1, "n[0, 100]") expect_fail_all(xx, "i+[1,2)") expect_fail_all(xx, "i+[1,2]") expect_fail_all(xx, "i+[1,3)") expect_succ_all(xx, "i+[1,3]") expect_fail_all(xx, "i+(2,3]") expect_fail_all(xx, "i+[2,2]") expect_fail_all(xx, "i+(1,3)") expect_succ_all(xx, "i+[1,3]") expect_succ_all(xx, "i[1,)") expect_succ_all(xx, "i[,3]") expect_succ_all(Inf, "n(1,]") expect_succ_all(-Inf, "n[,1]") expect_succ_all(c(-Inf, 0, Inf), "n[,]") expect_fail_all(Inf, "n(1,)") expect_fail_all(-Inf, "n(,0]") expect_fail_all(c(-Inf, 0, Inf), "n(,]") expect_fail_all(c(-Inf, 0, Inf), "n(,)") xx = letters[1:3] expect_succ_all(xx, "s+[1,]") expect_succ_all(xx, "s+[1,1]") expect_fail_all(xx, "s+[2]") expect_fail_all(NA_character_, "s+[1]") expect_fail_all(NA, "s+[1]") xx = factor(letters[1:3]) expect_succ_all(xx, "f+[1,]") expect_succ_all(xx, "f+[1,1]") expect_fail_all(xx, "f+[2]") expect_fail_all(NA_integer_, "f+[1]") expect_fail_all(NA_character_, "f+[1]") expect_fail_all(NA, "f+[1]") expect_succ_all(1, "n+()") expect_succ_all(1, "n+[]") expect_succ_all(Inf, "n+[]") expect_succ_all(Inf, "n+(]") expect_succ_all(-Inf, "n+[)") expect_fail_all(Inf, "n+()") expect_fail_all(Inf, "n+[)") expect_fail_all(-Inf, "n+(]") expect_error(qassert(iris, "d+[1]"), "Bound checks") }) test_that("non-atomic types", { expect_succ_all(function() 1, "*") expect_fail_all(function() 1, "b") expect_succ_all(function() 1, "*") expect_succ_all(NULL, "0?") expect_fail_all(xi, "0") expect_fail_all(NULL, "0+") expect_succ_all(NULL, "00") expect_fail_all(xe, "b") expect_fail_all(xf, "b") expect_fail_all(as.symbol("x"), "n") expect_fail_all(xd, "a") }) test_that("atomic types", { expect_succ_all(NULL, "a") expect_succ_all(xb, "a+") expect_fail_all(xb, "A+") expect_succ_all(xi, "a+") expect_fail_all(xi, "A+") expect_succ_all(xi, "n+") expect_fail_all(xi, "N+") expect_succ_all(xr, "n+") expect_fail_all(xr, "N+") expect_succ_all(xr, "a+") expect_fail_all(xr, "A+") expect_succ_all(xm, "a+") expect_fail_all(xm, "A+") expect_fail_all(xl, "a+") expect_fail_all(xl, "A+") expect_fail_all(xe, "a+") expect_succ_all(xf, "a+") expect_fail_all(NULL, "v") expect_succ_all(xb, "v+") expect_fail_all(xb, "V+") expect_succ_all(xi, "v+") expect_fail_all(xi, "V+") expect_succ_all(xr, "v+") expect_fail_all(xr, "V+") expect_fail_all(xm, "v+") expect_fail_all(xm, "V+") expect_fail_all(xl, "v+") expect_fail_all(xl, "V+") expect_fail_all(xe, "v+") expect_fail_all(xf, "V+") }) test_that("optional chars", { expect_succ_all(TRUE, "b*") expect_succ_all(TRUE, "b=1") expect_succ_all(TRUE, "b>=0") expect_succ_all(TRUE, "b>0") expect_succ_all(TRUE, "b<2") expect_fail_all(TRUE, "b=2") expect_fail_all(TRUE, "b>=2") expect_fail_all(TRUE, "b>2") expect_fail_all(TRUE, "b<0") }) test_that("malformated pattern", { expect_error(qassert(1, ""), "[Ee]mpty") # expect_warning(expect_error(qassert(1, "ä")), "locale") expect_error(qassert(1, "nn"), "length definition") expect_error(qassert(1, "n="), "length definition") expect_error(qassert(1, "n=="), "length definition") expect_error(qassert(1, "n==="), "length definition") expect_error(qassert(1, "n?1"), "bound definition") expect_error(qassert(1, "n>")) expect_error(qassert(1, "nö")) expect_error(qassert(1, "n\n")) expect_error(qassert(1, "n+a"), "opening") expect_error(qassert(1, "n+["), "bound") expect_error(qassert(1, "n+[1"), "lower") expect_error(qassert(1, "n+[x,]"), "lower") expect_error(qassert(1, "n+[,y]"), "upper") expect_error(qassert(1, "n*("), "bound definition") expect_error(qassert(1, "n*]"), "bound definition") expect_error(qassert(1, "n*(1)xx"), "Additional chars found") expect_error(qassert(1, TRUE), "be a string") expect_error(qassert(1, NA_character_), "not be NA") expect_error(qtest(1, TRUE), "be a string") expect_error(qtest(1, NA_character_), "not be NA") }) test_that("we get some output", { expect_error(qassert(1, "b"), "logical") expect_error(qassert(1, "l"), "list") expect_error(qassert(1:2, "n?"), "length <=") }) test_that("empty vectors", { expect_succ_all(integer(0), "i*") expect_succ_all(integer(0), "i*[0,0]") expect_succ_all(integer(0), "n[0,0]") expect_fail_all(integer(0), "r[0,0]") expect_fail_all(integer(0), "*+") expect_succ_all(TRUE, character(0)) }) test_that("logicals are not numeric", { expect_fail_all(TRUE, "i") expect_fail_all(TRUE, "I") expect_fail_all(TRUE, "n") expect_fail_all(TRUE, "N") }) test_that("data frames are not lists", { expect_fail_all(iris, "l") expect_fail_all(iris, "L") }) test_that("error messages are properly generated", { expect_error(qassert(1, "N22"), "== 22") expect_error(qassert(1:3, "N?"), "<= 1") expect_error(qassert(integer(0), "N+"), ">= 1") expect_error(qassert(1, "N[2,]"), ">= 2") expect_error(qassert(1, "N(2,]"), "> 2") expect_error(qassert(1, "N[,0]"), "<= 0") expect_error(qassert(1, "N[,0)"), "< 0") expect_error(qassert(Inf, "N[)"), "!= Inf") expect_error(qassert(-Inf, "N(]"), "!= -Inf") }) checkmate/tests/testthat/test_checkFactor.R0000644000176200001440000000330512762012005020572 0ustar liggesuserscontext("checkFactor") test_that("checkFactor", { myobj = factor(letters[1:2]) expect_succ_all(Factor, myobj) myobj = letters[1:2] expect_fail_all(Factor, myobj) x = factor(c("a", "b"), levels = c("a", "b")) expect_true(testFactor(x)) expect_false(testFactor(integer(1))) expect_false(testFactor("a")) expect_true(testFactor(factor())) # expect_false(testFactor(integer(0))) expect_false(testFactor(NULL)) expect_true(testFactor(x, levels = rev(levels(x)))) expect_true(testFactor(x, empty.levels.ok = FALSE)) expect_true(testFactor(x, ordered = FALSE)) expect_false(testFactor(x, levels = c("a"))) expect_false(testFactor(x, levels = c("a", "b", "c"))) x = factor(c("a", "b"), levels = c("a", "b", "c"), ordered = TRUE) expect_true(testFactor(x, empty.levels.ok = TRUE)) expect_false(testFactor(x, empty.levels.ok = FALSE)) expect_true(testFactor(x, ordered = TRUE)) expect_false(testFactor(x, ordered = FALSE)) x = factor(c("a", "b"), levels = c("a", "b", "c")) expect_error(assertFactor(1), "factor") expect_error(assertFactor(x, levels = c("a")), "levels") expect_error(assertFactor(x, empty.levels.ok = FALSE), "empty") expect_error(assertFactor(x, ordered = TRUE), "ordered") x = as.ordered(x) expect_error(assertFactor(x, ordered = FALSE), "unordered") x = factor(c("a", "b")) expect_true(testFactor(x, n.levels = 2)) expect_true(testFactor(x, min.levels = 2)) expect_true(testFactor(x, max.levels = 2)) expect_false(testFactor(x, n.levels = 1)) expect_false(testFactor(x, min.levels = 3)) expect_false(testFactor(x, max.levels = 1)) expect_error(testFactor(x, n.levels = NA)) expect_error(assertFactor(x, n.levels = 1), "exactly 1 level") }) checkmate/tests/testthat/test_checkTibble.R0000644000176200001440000000065013162135300020554 0ustar liggesuserscontext("checkTibble") test_that("checkTibble", { skip_if_not_physically_installed("tibble") expect_false(testTibble(iris)) expect_true("tibble" %in% loadedNamespaces()) x = tibble::as_tibble(iris) expect_succ_all("DataFrame", x) expect_succ_all("Tibble", x) expect_fail_all("Tibble", iris) expect_true(testTibble(x, min.rows = 1, ncols = 5)) expect_false(testTibble(x, min.rows = 1000, ncols = 5)) }) checkmate/tests/testthat/test_checkArray.R0000644000176200001440000000275412762012005020441 0ustar liggesuserscontext("checkArray") test_that("checkArray", { myobj = array(1:2) expect_succ_all(Array, myobj) myobj = 1:2 expect_fail_all(Array, myobj) x = array(dim = c(2, 3)) expect_true(testArray(x)) expect_true(testArray(x, d = 2L)) expect_false(testArray(x, d = 1L)) expect_true(testArray(x, min.d = 0L)) expect_true(testArray(x, min.d = 1L)) expect_true(testArray(x, max.d = 2L)) expect_true(testArray(x, max.d = 3L)) expect_false(testArray(x, min.d = 3L)) expect_false(testArray(x, max.d = 1L)) x[2,2] = NA expect_true(testMatrix(x)) expect_false(testMatrix(x, any.missing = FALSE)) expect_false(testArray(x, any.missing = FALSE)) expect_error(assertArray(iris)) x = array(1:27, dim = c(3, 3, 3)) expect_true(testArray(x, mode = "integer")) expect_true(testArray(x, mode = "numeric")) expect_true(testArray(x, mode = "atomic")) expect_false(testArray(x, mode = "double")) expect_false(testArray(x, mode = "character")) expect_false(testArray(x, mode = "list")) x = array(list(1, 1), dim = c(1, 2)) expect_true(testArray(x)) expect_true(testArray(x, mode = "list")) expect_false(testArray(x, mode = "atomic")) expect_false(testArray(x, mode = "numeric")) expect_error(assertArray(1:3), "array") }) test_that("type guessing works", { x = array(1:4) expect_match(checkCharacter(x), "array") x = array(1:4, dim = c(2, 2)) expect_match(checkCharacter(x), "matrix") x = array(1:9, dim = c(3, 3, 3)) expect_match(checkCharacter(x), "array") }) checkmate/tests/testthat/test_checkInt.R0000644000176200001440000000140112762012005020101 0ustar liggesuserscontext("checkInt") test_that("checkInt", { myobj = 1L expect_succ_all(Int, myobj) myobj = 1.1 expect_fail_all(Int, myobj) expect_false(testInt(integer(0))) expect_false(testInt(NULL)) expect_false(testInt(FALSE)) expect_false(testInt(TRUE)) expect_true(testInt(1L)) expect_true(testInt(1.)) expect_false(testInt(NA)) expect_true(testInt(NA_real_, na.ok = TRUE)) expect_false(testInt(1:2)) expect_false(testInt("")) expect_error(assertInt(2+3i), "integerish") }) test_that("bounds of vectors with only missings are not checked", { expect_true(checkInt(NA, na.ok = TRUE, lower = 1)) expect_true(checkInt(NA_character_, na.ok = TRUE, upper = 10)) expect_fail_all(Int, 0L, lower = 1L) expect_fail_all(Int, 100L, upper = 10L) }) checkmate/tests/testthat/test_assert.R0000644000176200001440000000221212762012005017653 0ustar liggesuserscontext("assert") test_that("assert w/ check*", { x = NULL expect_true(assert(checkNull(x), checkDataFrame(x))) expect_true(assert(checkNull(x))) grepme = iris expect_true(assert(checkNull(grepme), checkDataFrame(grepme))) expect_error(assert(checkNull(grepme), checkNumeric(grepme)), "One of") expect_error(assert(checkNull(grepme), checkNumeric(grepme)), "grepme") x = 1 expect_true(assert(checkNumeric(x), checkCount(x))) expect_true(assert(checkNumeric(x), checkCount(x), combine = "or")) expect_true(assert(checkNumeric(x), checkCount(x), combine = "and")) x = 1.1 expect_true(assert(checkNumeric(x), checkCount(x), combine = "or")) expect_error(assert(checkNumeric(x), checkCount(x), combine = "and")) x = "a" expect_true(assert(checkString(x))) expect_error(assert(checkNumeric(x), checkCount(x), combine = "or")) expect_error(assert(checkNumeric(x), checkCount(x), combine = "and")) }) test_that("bug #69", { sub = subset = 1:150 res = assert(checkIntegerish(subset), checkLogical(subset, len = 150)) expect_true(res) res = assert(checkIntegerish(sub), checkLogical(sub, len = 150)) expect_true(res) }) checkmate/tests/testthat/test_checkClass.R0000644000176200001440000000203313036122224020416 0ustar liggesuserscontext("checkClass") test_that("checkClass", { myobj = 1 expect_succ_all(Class, myobj, "numeric") expect_fail_all(Class, myobj, "integer") expect_true(testClass(NULL, "NULL")) expect_false(testClass(NULL, "")) expect_true(testClass(1, "numeric")) expect_true(testClass(1L, "integer")) expect_false(testClass(1, "integer")) foo = 1 class(foo) = c("a", "b") expect_true(testClass(foo, "a")) expect_true(testClass(foo, "b")) expect_false(testClass(foo, "c")) expect_true(testClass(foo, "a", ordered=TRUE)) expect_false(testClass(foo, "b", ordered=TRUE)) expect_true(testClass(foo, c("a", "b"), ordered=TRUE)) expect_false(testClass(foo, c("b", "a"), ordered=TRUE)) foo = 1 class(foo) = c("a", "b") expect_error(assertClass(foo, "c"), "Must have class 'c', but has classes 'a','b'") expect_error(assertClass(foo, "b", ordered=TRUE), "Must have class 'b' in position 1, but has classes 'a','b'") foo = 1 class(foo) = "a" expect_error(assertClass(foo, "c"), "Must have class 'c', but has class 'a'") }) checkmate/tests/testthat/test_checkNamed.R0000644000176200001440000000356413154206616020420 0ustar liggesuserscontext("checkNamed") test_that("checkNamed", { # checkNamed is deprecated. Skip tests on all platforms except local. skip_on_cran() skip_on_travis() skip_on_appveyor() myobj = setNames(1:3, letters[1:3]) expect_succ_all(Named, myobj) myobj = 1:3 expect_fail_all(Named, myobj) expect_true(testNamed(integer(0))) expect_true(testNamed(NULL)) expect_true(testNamed(setNames(integer(0), character(0)))) x = setNames(1:2, c("a", ".a")) expect_true(testNamed(x)) expect_true(testNamed(x, "unique")) expect_true(testNamed(x, "strict")) expect_false(testNamed(1)) expect_false(testNamed(setNames(x, NA_character_))) expect_false(testNamed(setNames(x, NA_integer_))) expect_false(testNamed(setNames(x, ""))) x = setNames(1:2, c("a", "a")) expect_true(testNamed(x)) expect_false(testNamed(x, "unique")) x = setNames(1:2, c("a", "1")) expect_true(testNamed(x)) expect_false(testNamed(x, "strict")) x = setNames(1:2, c("a", "..1")) expect_true(testNamed(x)) expect_false(testNamed(x, "strict")) x = setNames(1, "") expect_error(assertNamed(x), "named") x = setNames(1:2, c("a", "a")) expect_error(assertNamed(x, "unique"), "uniquely") expect_true(testNamed(setNames(1, "x"), type = "strict")) expect_true(testNamed(setNames(1, "..x"), type = "strict")) expect_true(testNamed(setNames(1, "x_1"), type = "strict")) expect_true(testNamed(setNames(1, "x."), type = "strict")) expect_false(testNamed(setNames(1, "1"), type = "strict")) expect_false(testNamed(setNames(1, ".1"), type = "strict")) expect_false(testNamed(setNames(1, "..1"), type = "strict")) expect_false(testNamed(setNames(1, "x "), type = "strict")) expect_false(testNamed(setNames(1, "ä"), type = "strict")) expect_error(assertNamed(x, "unique"), "uniquely") x = setNames(1:2, c("a", "1")) expect_error(assertNamed(x, "strict"), "naming conventions") }) checkmate/tests/testthat/test_checkTRUE.R0000644000176200001440000000026513007055223020137 0ustar liggesuserscontext("checkTRUE") test_that("checkTRUE", { expect_succ_all(TRUE, TRUE) expect_fail_all(TRUE, 1) expect_false(test_true(NA)) expect_true(test_true(NA, na.ok = TRUE)) }) checkmate/tests/testthat/test_checkChoice.R0000644000176200001440000000261413167073256020567 0ustar liggesuserscontext("checkChoice") test_that("checkChoice", { myobj = 1 expect_succ_all(Choice, myobj, 1:3) myobj = 0 expect_fail_all(Choice, myobj, 1:3) expect_false(testChoice(character(0), letters)) expect_false(testChoice(NULL, letters)) expect_false(testChoice(1, NULL)) expect_error(testChoice(list(1), as.list(iris)), "atomic") expect_false(testChoice(factor("a"), letters)) expect_true(testChoice(factor("a"), factor(letters))) expect_true(testChoice(1., 1:2)) expect_false(testChoice(NULL, NULL)) expect_false(testChoice(NULL, letters, null.ok = FALSE)) expect_true(checkChoice(NULL, letters, null.ok = TRUE)) expect_true(testChoice(1L, 1:10)) expect_false(testChoice("ab", letters)) expect_false(testChoice(NA_integer_, 1:10)) expect_false(testChoice(1:2, 1:10)) expect_error(assertChoice(-1, 1:2), "element of") expect_error(assertChoice(1L, list()), "atomic") expect_true(grepl("atomic scalar", checkChoice(1:2, 1:10), fixed = TRUE)) expect_true(grepl("types do not match", checkChoice(factor("a"), letters), fixed = TRUE)) expect_true(grepl("'foo'", checkChoice("foo", letters), fixed = TRUE)) }) test_that("checkChoice / fastmatch", { x = "c" y = letters[1:5] res = testChoice(x, y) expect_true(res) expect_null(attr(y, ".match.hash")) res = testChoice(x, y, fmatch = TRUE) expect_true(res) expect_class(attr(y, ".match.hash"), "match.hash") }) checkmate/tests/testthat/helper.R0000644000176200001440000000610013167125351016603 0ustar liggesusersexpect_expectation_successful = function(expr, info = NULL, label = NULL) { res = tryCatch(expr, expectation = function(e) e) expect_is(res, "expectation_success", info = info, label = label) } expect_expectation_failed = function(expr, pattern = NULL, info = NULL, label = NULL) { x = tryCatch(expr, expectation = function(e) e) expect_is(x, "expectation_failure", info = info, label = label) } skip_if_not_physically_installed = function(x) { loc = find.package(x, quiet = TRUE) if (length(loc) == 0L) skip(sprintf("Package '%s' is not installed", x)) } expect_succ_all = function(part, x, ..., cc = as.character(substitute(part)), lc = convertCamelCase(cc)) { xn = deparse(substitute(x)) # check null.ok if it is in formals s = paste0("check", cc) fun = match.fun(s) if ("null.ok" %in% names(formals(fun))) { dots = list(...) dots["x"] = list(NULL) dots$null.ok = TRUE expect_true(do.call(fun, dots)) } s = paste0("check", cc) fun = match.fun(s) expect_true(fun(x, ...), label = s) s = paste0("check_", lc) fun = match.fun(s) expect_true(fun(x, ...), label = s) s = paste0("test", cc) fun = match.fun(s) expect_true(fun(x, ...), info = s, label = xn) s = paste0("test_", lc) fun = match.fun(s) expect_true(fun(x, ...), info = s, label = xn) s = paste0("assert", cc) fun = match.fun(s) expect_identical(fun(x, ...), x, info = s, label = xn) s = paste0("assert_", lc) fun = match.fun(s) expect_identical(fun(x, ...), x, info = s, label = xn) s = paste0("expect_", lc) fun = match.fun(s) expect_expectation_successful(fun(x, ...), info = s, label = xn) invisible(TRUE) } expect_fail_all = function(part, x, ..., cc = as.character(substitute(part)), lc = convertCamelCase(cc)) { xn = deparse(substitute(x)) # check null.ok if it is in formals s = paste0("check", cc) fun = match.fun(s) if ("null.ok" %in% names(formals(fun))) { dots = list(...) dots["x"] = list(NULL) dots$null.ok = FALSE expect_true(grepl("'NULL'", do.call(fun, dots), fixed = TRUE)) } s = paste0("check", cc) fun = match.fun(s) res = fun(x, ...) expect_true(is.character(res) && nzchar(res), info = s, label = xn) s = paste0("test", cc) fun = match.fun(s) expect_false(fun(x, ...), info = s, label = xn) s = paste0("test_", lc) fun = match.fun(s) expect_false(fun(x, ...), info = s, label = xn) s = paste0("assert", cc) fun = match.fun(s) expect_error(fun(x, ..., .var.name = xn), xn, info = s, label = xn) expect_error(fun(x, ...), "'x'", info = s, label = xn) s = paste0("assert_", lc) fun = match.fun(s) expect_error(fun(x, ..., .var.name = xn), xn, info = s, label = xn) expect_error(fun(x, ...), "'x'", info = s, label = xn) s = paste0("expect_", lc) fun = match.fun(s) expect_expectation_failed(fun(x, ...), pattern = "x", info = s, label = xn) expect_expectation_failed(fun(x, ..., label = xn), pattern = xn, info = s, label = xn) invisible(TRUE) } vlapply = function (x, fun, ..., use.names = TRUE) { vapply(X = x, FUN = fun, ..., FUN.VALUE = NA, USE.NAMES = use.names) } checkmate/tests/testthat/test_asType.R0000644000176200001440000000454112762012005017626 0ustar liggesuserscontext("asType") test_that("asInteger", { xi = 1:5 xd = as.double(1:5) xc = as.complex(1:5) expect_equal(asInteger(xi), xi) expect_equal(asInteger(xd), xi) expect_equal(asInteger(xc), xi) expect_equal(asInteger(NA), NA_integer_) expect_equal(names(asInteger(xi)), names(xi)) expect_equal(names(asInteger(xd)), names(xd)) expect_equal(names(asInteger(xc)), names(xc)) names(xi) = names(xd) = names(xc) = letters[1:5] expect_equal(names(asInteger(xi)), names(xi)) expect_equal(names(asInteger(xd)), names(xd)) expect_equal(names(asInteger(xc)), names(xc)) y = "a" expect_error(asInteger(y), "'y'") expect_error(asInteger(3+1i)) expect_error(asInteger(iris)) expect_error(asInteger(NA, any.missing = FALSE), "missing") }) test_that("asInt", { xi = 1L xd = 1. xc = as.complex(1) expect_equal(names(asInt(xi)), names(xi)) expect_equal(names(asInt(xd)), names(xd)) expect_equal(names(asInt(xc)), names(xc)) names(xi) = names(xd) = names(xc) = "a" expect_equal(names(asInt(xi)), names(xi)) expect_equal(names(asInt(xd)), names(xd)) expect_equal(names(asInt(xc)), names(xc)) expect_error(asInt(letters[1:2]), "integerish") expect_error(asInt(1:2), "length 1") expect_equal(asInt(xi), xi) expect_equal(asInt(xd), xi) expect_equal(asInt(xc), xi) expect_error(asInt(NA), "NA") expect_equal(asInt(NA, na.ok = TRUE), NA_integer_) y = "a" expect_error(asInt(y), "'y'") expect_error(asInt(3+1i)) expect_error(asInt(iris)) expect_error(asInt(xi, lower = 2), ">=") }) test_that("asCount", { xi = 1L xd = 1. xc = as.complex(1) expect_equal(names(asCount(xi)), names(xi)) expect_equal(names(asCount(xd)), names(xd)) expect_equal(names(asCount(xc)), names(xc)) names(xi) = names(xd) = names(xc) = "a" expect_equal(names(asCount(xi)), names(xi)) expect_equal(names(asCount(xd)), names(xd)) expect_equal(names(asCount(xc)), names(xc)) expect_error(asCount(letters[1:2]), "count") expect_error(asCount(1:2), "length 1") expect_equal(asCount(xi), xi) expect_equal(asCount(xd), xi) expect_equal(asCount(xc), xi) expect_error(asCount(NA), "NA") expect_equal(asCount(NA, na.ok = TRUE), NA_integer_) y = "a" expect_error(asCount(y), "'y'") expect_error(asCount(3+1i)) expect_error(asCount(iris)) expect_error(asCount(0, positive = TRUE)) expect_equal(asCount(1, positive = FALSE), 1L) }) checkmate/tests/testthat/test_checkAtomic.R0000644000176200001440000000256212766720671020617 0ustar liggesuserscontext("checkAtomic") li = list( list = list(1, 2), factor = factor("a"), integer = 1:2, NULL = NULL, data.frame = iris ) test_that("checkAtomic", { myobj = 1:2 expect_succ_all(Atomic, myobj) myobj = iris expect_fail_all(Atomic, myobj) expect_true(testAtomic(integer(0))) expect_true(testAtomic(NULL)) expect_true(testAtomic(1)) expect_true(testAtomic(integer(0))) expect_true(testAtomic(factor(1))) expect_true(testAtomic(NA, any.missing = TRUE)) expect_false(testAtomic(NA, any.missing = FALSE)) expect_false(testAtomic(NA, all.missing = FALSE)) expect_true(testAtomic(1, len=1)) expect_false(testAtomic(1, len=0)) expect_true(testAtomic(1, min.len=0)) expect_false(testAtomic(1, min.len=2)) expect_true(testAtomic(1, max.len=1)) expect_false(testAtomic(1, max.len=0)) expect_true(testAtomic(1, unique=TRUE)) expect_false(testAtomic(1, min.len=2)) expect_true(testAtomic(1, max.len=1)) expect_false(testAtomic(1, max.len=0)) expect_true(testAtomic(1, unique=TRUE)) expect_true(testAtomic(c(1,1), unique=FALSE)) expect_false(testAtomic(c(1,1), unique=TRUE)) expect_true(testAtomic(1, names="unnamed")) expect_true(testAtomic(setNames(1, "x"), names="named")) expect_false(testAtomic(1, names="unique")) expect_error(assertAtomic(iris), "atomic") expect_equal(vlapply(li, is.atomic), vlapply(li, testAtomic)) }) checkmate/tests/testthat/test_checkLogical.R0000644000176200001440000000112512762012005020724 0ustar liggesuserscontext("checkLogical") test_that("checkLogical", { myobj = TRUE expect_succ_all(Logical, myobj) myobj = 1 expect_fail_all(Logical, myobj) expect_true(testLogical(logical(0))) expect_false(testLogical(NULL)) expect_true(testLogical(TRUE)) expect_true(testLogical(NA)) expect_true(testLogical(NA_real_)) expect_true(testLogical(FALSE)) expect_false(testLogical(NA, any.missing=FALSE)) expect_false(testLogical(NA, all.missing=FALSE)) expect_false(testLogical(iris)) expect_true(testLogical(c(TRUE, FALSE), min.len = 2)) expect_error(assertLogical(1), "logical") }) checkmate/tests/testthat/test_checkNumber.R0000644000176200001440000000212612762012005020604 0ustar liggesuserscontext("checkNumber") test_that("checkNumber", { myobj = 1 expect_succ_all(Number, myobj) myobj = "a" expect_fail_all(Number, myobj) expect_false(testNumber(integer(0))) expect_false(testNumber(NULL)) expect_false(testNumber(TRUE)) expect_false(testNumber(FALSE)) expect_true(testNumber(1L)) expect_true(testNumber(1.)) expect_false(testNumber(NA)) expect_false(testNumber(NaN)) expect_true(testNumber(NaN, na.ok = TRUE)) expect_true(testNumber(NA_real_, na.ok = TRUE)) expect_false(testNumber(1:2)) expect_false(testNumber("")) expect_true(testNumber(Inf)) expect_true(testNumber(-Inf)) expect_error(assertNumber(Inf, finite = TRUE), "finite") expect_error(assertNumber(-Inf, finite = TRUE), "finite") expect_false(testNumber(TRUE)) expect_error(assertNumber(2+3i), "number") }) test_that("bounds of vectors with only missings are not checked", { expect_true(checkNumber(NA, na.ok = TRUE, lower = 1)) expect_true(checkNumber(NA_character_, na.ok = TRUE, upper = 10)) expect_fail_all(Number, 0, lower = 1) expect_fail_all(Number, 100, upper = 10) }) checkmate/tests/testthat/test_checkAtomicVector.R0000644000176200001440000000337412766720672022005 0ustar liggesuserscontext("checkAtomicVector") test_that("checkAtomicVector", { myobj = 1:2 expect_succ_all(AtomicVector, myobj) myobj = NULL expect_fail_all(AtomicVector, myobj) expect_true(testAtomicVector(integer(0))) expect_false(testAtomicVector(NULL)) expect_true(testAtomicVector(1)) expect_true(testAtomicVector(integer(0))) expect_true(testAtomicVector(factor(1))) expect_true(testAtomicVector(NA, any.missing = TRUE)) expect_false(testAtomicVector(NA, any.missing = FALSE)) expect_false(testAtomicVector(NA, all.missing = FALSE)) expect_true(testAtomicVector(1, len=1)) expect_false(testAtomicVector(1, len=0)) expect_true(testAtomicVector(1, min.len=0)) expect_false(testAtomicVector(1, min.len=2)) expect_true(testAtomicVector(1, max.len=1)) expect_false(testAtomicVector(1, max.len=0)) expect_true(testAtomicVector(1, unique=TRUE)) expect_false(testAtomicVector(1, min.len=2)) expect_true(testAtomicVector(1, max.len=1)) expect_false(testAtomicVector(1, max.len=0)) expect_true(testAtomicVector(1, unique=TRUE)) expect_true(testAtomicVector(c(1,1), unique=FALSE)) expect_false(testAtomicVector(c(1,1), unique=TRUE)) expect_true(testAtomicVector(1, names="unnamed")) expect_true(testAtomicVector(setNames(1, "x"), names="named")) expect_false(testAtomicVector(1, names="unique")) expect_error(assertAtomicVector(iris), "atomic") li = list(list = list(1, 2), factor = factor("a"), integer = 1:2, NULL = NULL, data.frame = iris, matrix = matrix(1:9)) expected = setNames(c(FALSE, TRUE, TRUE, FALSE, FALSE, FALSE), names(li)) expect_equal(expected, vlapply(li, testAtomicVector)) }) test_that("type guessing works (#48)", { x = structure(list(1:4, letters[1:3]), dim = c(2, 1)) expect_match(checkAtomic(x), "list") }) checkmate/tests/testthat/test_anyMissing.R0000644000176200001440000000457512766720672020535 0ustar liggesuserscontext("anyMissing") xb = logical(10) xi = integer(10) xd = double(10) xc = complex(10) xs = letters[1:10] xl = as.list(1:10) xm = matrix(1:9, 3) xf = data.frame(a=1:5, b=1:5) test_that("anyMissing", { expect_false(anyMissing(integer(0))) expect_false(anyMissing(xb)) expect_false(anyMissing(xi)) expect_false(anyMissing(xd)) expect_false(anyMissing(xc)) expect_false(anyMissing(xs)) expect_false(anyMissing(xl)) expect_false(anyMissing(xm)) expect_false(anyMissing(xf)) xb[5] = xi[5] = xd[5] = xc[5] = xs[5] = xm[2, 2] = xf$b[3] = NA xl[5] = list(NULL) expect_true(anyMissing(xb)) expect_true(anyMissing(xi)) expect_true(anyMissing(xd)) expect_true(anyMissing(xc)) expect_true(anyMissing(xs)) expect_true(anyMissing(xl)) expect_true(anyMissing(xm)) expect_true(anyMissing(xf)) expect_false(anyMissing(as.raw(1))) expect_false(anyMissing(NULL)) expect_error(anyMissing(as.symbol("a")), "supported") }) test_that("allMissing", { expect_true(allMissing(integer(0))) expect_false(allMissing(xb)) expect_false(allMissing(xi)) expect_false(allMissing(xd)) expect_false(allMissing(xc)) expect_false(allMissing(xs)) expect_false(allMissing(xl)) expect_false(allMissing(xm)) expect_false(allMissing(xf)) xb[5] = xi[5] = xd[5] = xc[5] = xm[2, 2] = xf$b[3] = NA xl[5] = list(NULL) expect_false(allMissing(xb)) expect_false(allMissing(xi)) expect_false(allMissing(xd)) expect_false(allMissing(xc)) expect_false(allMissing(xs)) expect_false(allMissing(xl)) expect_false(allMissing(xm)) expect_false(allMissing(xf)) xb[] = xi[] = xd[] = xc[] = xm[] = xs = NA xl = list(NULL, NULL) xf$a = xf$b = NA expect_true(allMissing(xb)) expect_true(allMissing(xi)) expect_true(allMissing(xd)) expect_true(allMissing(xc)) expect_true(allMissing(xs)) expect_true(allMissing(xl)) expect_true(allMissing(xm)) expect_true(allMissing(xf)) expect_false(allMissing(as.raw(1))) expect_false(allMissing(NULL)) expect_error(allMissing(as.symbol("a")), "supported") }) test_that("anyMissing and allMissing work correctly with data.frames", { df = data.frame(a = 1:2, b = 2:1) expect_false(anyMissing(df)) expect_false(allMissing(df)) df$b[1] = NA expect_true(anyMissing(df)) expect_false(allMissing(df)) df$b[2] = NA expect_true(anyMissing(df)) expect_true(allMissing(df)) expect_false(all(vlapply(df, allMissing))) }) checkmate/tests/testthat/test_checkDate.R0000644000176200001440000000640513167111024020236 0ustar liggesuserscontext("checkDate") test_that("checkDate", { x = Sys.Date() expect_succ_all(Date, x) expect_fail_all(Date, 1) expect_true(testDate(x, lower = 1)) expect_true(testDate(x, upper = as.integer(x + 2))) expect_error(assertDate(x, lower = x + 2), ">=") expect_error(assertDate(x, upper = x - 2), "<=") expect_true(testDate(x, upper = x + 2)) expect_false(testDate(x, upper = x - 2)) expect_true(testDate(x, lower = x - 2)) expect_false(testDate(x, lower = x + 2)) expect_error(assertDate(x, lower = 1:2), "single") expect_error(assertDate(x, lower = NA), "single") expect_error(assertDate(x, lower = integer(0)), "single") expect_error(assertDate(x, upper = 1:2), "single") expect_error(assertDate(x, upper = NA), "single") expect_error(assertDate(x, upper = integer(0)), "single") x = as.Date(NA) expect_error(assertDate(x, any.missing = FALSE), "missing") x = rep(Sys.Date(), 2) expect_error(assertDate(x, unique = TRUE), "duplicated") expect_error(assertDate(letters, unique = TRUE), "character") }) test_that("NAs are ignored for dates' lower-bound", { # Define and test a nomal date vector, and an empty date vector. d <- as.Date(c("2015-01-01", "2016-01-01", NA_character_, "2017-01-01")) empty <- as.Date(character(0)) nas <- as.Date(NA_character_, NA_character_, NA_character_) # Bounds pass/fail appropriately when missing values are legal. expect_true( testDate(d , lower = "1980-01-01", any.missing = TRUE )) expect_false(testDate(d , lower = "2016-01-01", any.missing = TRUE )) # Bounds are ignored when missing values are illegal (and the vector contains missing values). expect_false(testDate(d , lower = "1980-01-01", any.missing = FALSE)) expect_false(testDate(d , lower = "2016-01-01", any.missing = FALSE)) # Zero-length date vectors never fail with a lower bound. expect_true( testDate(empty, lower ="2030-01-01", any.missing = TRUE )) expect_true( testDate(empty, lower ="2030-01-01", any.missing = FALSE)) # NA date vectors expect_true( testDate(nas , lower ="2030-01-01", any.missing = TRUE )) expect_false(testDate(nas , lower ="2030-01-01", any.missing = FALSE)) }) test_that("NAs are ignored for dates' upper-bound", { # Define and test a nomal date vector, and an empty date vector. d <- as.Date(c("2015-01-01", "2016-01-01", NA_character_, "2017-01-01")) empty <- as.Date(character(0)) nas <- as.Date(NA_character_, NA_character_, NA_character_) # Bounds pass/fail appropriately when missing values are legal. expect_true( testDate(d , upper = "2020-01-01", any.missing = TRUE )) expect_false(testDate(d , upper = "2016-01-01", any.missing = TRUE )) # Bounds are ignored when missing values are illegal (and the vector contains missing values). expect_false(testDate(d , upper = "2020-01-01", any.missing = FALSE)) expect_false(testDate(d , upper = "2016-01-01", any.missing = FALSE)) # Zero-length date vectors never fail with a upper bound. expect_true( testDate(empty, upper = "2000-01-01", any.missing = FALSE)) expect_true( testDate(empty, upper = "2000-01-01", any.missing = FALSE)) # NA date vectors expect_true( testDate(nas , lower ="2030-01-01", any.missing = TRUE )) expect_false(testDate(nas , lower ="2030-01-01", any.missing = FALSE)) }) checkmate/tests/testthat/test_checkFlag.R0000644000176200001440000000073012762012005020224 0ustar liggesuserscontext("checkFlag") test_that("checkFlag", { myobj = TRUE expect_succ_all(Flag, myobj) myobj = NA expect_fail_all(Flag, myobj) expect_false(testFlag(logical(0))) expect_false(testFlag(NULL)) expect_true(testFlag(TRUE)) expect_true(testFlag(FALSE)) expect_false(testFlag(NA)) expect_true(testFlag(NA, na.ok = TRUE)) expect_true(testFlag(NA_character_, na.ok = TRUE)) expect_false(testFlag(iris)) expect_error(assertFlag(1), "logical flag") }) checkmate/tests/testthat/test_anyInfinite.R0000644000176200001440000000141112762012005020627 0ustar liggesuserscontext("anyInfinite") test_that("anyInfinite", { xb = logical(10) xi = integer(10) xd = double(10) xc = complex(10) xl = as.list(1:10) xm = matrix(1:9, 3) xf = data.frame(a=1:5, b=1:5) expect_false(anyInfinite(NULL)) expect_false(anyInfinite(mean)) expect_false(anyInfinite(double(0))) expect_false(anyInfinite(xb)) expect_false(anyInfinite(xi)) expect_false(anyInfinite(xd)) expect_false(anyInfinite(xc)) expect_false(anyInfinite(xl)) expect_false(anyInfinite(xm)) expect_false(anyInfinite(xf)) xd[5] = xc[5] = xf$b[3] = Inf xl[5] = -Inf expect_true(anyInfinite(xd)) expect_true(anyInfinite(xc)) expect_true(anyInfinite(xl)) expect_true(anyInfinite(xf)) x = list(1, list(1, list(1, Inf))) expect_true(anyInfinite(x)) }) checkmate/tests/testthat/test_guessType.R0000644000176200001440000000262312762012005020350 0ustar liggesuserscontext("guessType") test_that("guessType", { xb = logical(10) xi = integer(10) xd = double(10) xc = complex(10) xs = letters[1:10] xl = as.list(1:10) xm = matrix(1:9, 3) xa = array(1:3) xf = data.frame(a=1:5, b=1:5) xx = 1; class(xx) = "Foo" xxx = 1; class(xxx) = c("Foo", "Bar") expect_equal(guessType(xb), "logical") expect_equal(guessType(xi), "integer") expect_equal(guessType(xd), "double") expect_equal(guessType(xc), "complex") expect_equal(guessType(xs), "character") expect_equal(guessType(xl), "list") expect_equal(guessType(xm), "matrix") expect_equal(guessType(xa), "array") expect_equal(guessType(xf), "data.frame") expect_equal(guessType(xx), "Foo") expect_equal(guessType(xxx), "Foo/Bar") expect_true(grepl("NULL'$", checkLogical(NULL))) expect_true(grepl("logical'$", checkInteger(xb))) expect_true(grepl("integer'$", checkLogical(xi))) expect_true(grepl("double'$", checkLogical(xd))) expect_true(grepl("complex'$", checkLogical(xc))) expect_true(grepl("character'$", checkLogical(xs))) expect_true(grepl("factor'$", checkLogical(factor(xs)))) expect_true(grepl("list'$", checkLogical(xl))) expect_true(grepl("matrix'$", checkLogical(xm))) expect_true(grepl("array'$", checkLogical(xa))) expect_true(grepl("frame'$", checkLogical(xf))) expect_true(grepl("Foo'$", checkLogical(xx))) expect_true(grepl("Foo/Bar'$", checkLogical(xxx))) }) checkmate/tests/testthat/test_checkSetEqual.R0000644000176200001440000000333713167073256021123 0ustar liggesuserscontext("checkSetEqual") test_that("checkSetEqual", { myobj = letters[3:1] expect_succ_all(SetEqual, myobj, letters[1:3]) expect_fail_all(SetEqual, myobj, letters[1:3], ordered = TRUE) myobj = letters[1:2] expect_fail_all(String, myobj, letters[1:3]) expect_true(testSetEqual(character(0), character(0))) expect_true(testSetEqual(character(0), character(0), ordered = TRUE)) expect_false(testSetEqual(character(0), letters)) expect_false(testSetEqual(letters, character(0))) expect_false(testSetEqual(NULL, letters)) expect_false(testSetEqual(NULL, letters, ordered = TRUE)) expect_false(testSetEqual(factor("a"), letters)) expect_true(testSetEqual(factor(letters), factor(letters))) expect_false(testSetEqual(letters, factor(letters))) expect_true(testSetEqual(1L, 1L)) expect_true(testSetEqual(1, 1L)) expect_true(testSetEqual(3:4, 3:4)) expect_true(testSetEqual(NA_integer_, NA_integer_)) expect_true(testSetEqual(1:2, 1:2, ordered = TRUE)) expect_false(testSetEqual(1:2, 2:1, ordered = TRUE)) expect_true(testSetEqual(NA, NA, ordered = TRUE)) expect_false(testSetEqual(NA_integer_, 1L, ordered = TRUE)) expect_false(testSetEqual(1L, NA_integer_, ordered = TRUE)) expect_false(testSetEqual(c(NA_integer_, 2L), 1:2, ordered = TRUE)) expect_true(testSetEqual(c(NA_integer_, 2L), c(NA_real_, 2), ordered = TRUE)) expect_error(assertSetEqual(1, 1:2), "equal to") expect_error(assertSetEqual(1L, list()), "atomic") }) test_that("checkSetEqual / fastmatch", { x = letters[5:1] y = letters[1:5] res = testSetEqual(x, y) expect_true(res) expect_null(attr(y, ".match.hash")) res = testSetEqual(x, y, fmatch = TRUE) expect_true(res) expect_class(attr(y, ".match.hash"), "match.hash") }) checkmate/tests/testthat/test_checkVector.R0000644000176200001440000000461212766720672020644 0ustar liggesuserscontext("checkVector") li = list( list = list(1, 2), factor = factor("a"), integer = 1:2, NULL = NULL, data.frame = iris ) test_that("checkVector", { myobj = 1:3 expect_succ_all(Vector, myobj) myobj = NULL expect_fail_all(Vector, myobj) expect_true(testVector(integer(0))) expect_false(testVector(NULL)) expect_true(testVector(1)) expect_true(testVector(integer(0))) expect_true(testVector(factor(1), strict = FALSE)) expect_false(testVector(factor(1), strict = TRUE)) expect_true(testVector(NA, any.missing = TRUE)) expect_false(testVector(NA, any.missing = FALSE)) expect_false(testVector(NA, all.missing = FALSE)) expect_true(testVector(1, len=1)) expect_false(testVector(1, len=0)) expect_true(testVector(1, min.len=0)) expect_false(testVector(1, min.len=2)) expect_true(testVector(1, max.len=1)) expect_false(testVector(1, max.len=0)) expect_true(testVector(1, unique=TRUE)) expect_false(testVector(1, min.len=2)) expect_true(testVector(1, max.len=1)) expect_false(testVector(1, max.len=0)) expect_true(testVector(1, unique=TRUE)) expect_true(testVector(c(1,1), unique=FALSE)) expect_false(testVector(c(1,1), unique=TRUE)) expect_true(testVector(1, names="unnamed")) expect_true(testVector(setNames(1, "x"), names="named")) expect_false(testVector(1, names="unique")) expect_equal(vlapply(li, is.vector), vlapply(li, testVector, strict = TRUE)) expected = setNames(c(TRUE, TRUE, TRUE, FALSE, TRUE), c("list", "factor", "integer", "NULL", "data.frame")) expect_equal(expected, vlapply(li, testVector, strict = FALSE)) expect_error(assertVector(iris, strict = TRUE), "vector") }) test_that("arguments any.missing and all.missing are checked", { x = 1 expect_error(checkVector(x, any.missing = 1), "flag") expect_error(checkVector(x, any.missing = NA), "missing") expect_error(checkVector(x, all.missing = 1), "flag") expect_error(checkVector(x, all.missing = NA), "missing") }) test_that("length is correctly reported", { x = 1:42 expect_true(grepl(42, checkVector(x, len = 1), fixed = TRUE)) expect_true(grepl(42, checkVector(x, min.len = 43), fixed = TRUE)) expect_true(grepl(42, checkVector(x, max.len = 1), fixed = TRUE)) expect_true(grepl(43, checkVector(x, len = 43), fixed = TRUE)) expect_true(grepl(43, checkVector(x, min.len = 43), fixed = TRUE)) expect_true(grepl(41, checkVector(x, max.len = 41), fixed = TRUE)) }) checkmate/tests/testthat/test_checkIntegerish.R0000644000176200001440000000376613064452167021505 0ustar liggesuserscontext("checkIntegerish") test_that("checkIntegerish", { myobj = 1 expect_succ_all(Integerish, myobj) myobj = 3.3 expect_fail_all(Integerish, myobj) x = 1 - 0.9 -.1 expect_true(testIntegerish(integer(0))) expect_false(testIntegerish(NULL)) expect_false(testIntegerish(TRUE)) expect_false(testIntegerish(FALSE)) expect_true(testIntegerish(1L)) expect_true(testIntegerish(c(-1, 0, 1))) expect_true(testIntegerish(1.)) expect_true(testIntegerish(x)) expect_true(testIntegerish(NA)) expect_true(testIntegerish(NaN)) expect_true(testIntegerish(c(1L, NA))) expect_true(testIntegerish(c(1, NA))) expect_true(testIntegerish(c(1, NaN))) expect_false(testIntegerish(1:2 + 0.0001)) expect_false(testIntegerish(-Inf)) expect_false(testIntegerish(Inf)) expect_true(testIntegerish(3+0i)) expect_false(testIntegerish(3-1i)) expect_true(testIntegerish(as.complex(NA))) expect_false(testIntegerish(3+2i)) expect_false(testIntegerish(list())) max = as.double(.Machine$integer.max) min = as.double(-.Machine$integer.max) expect_true(testIntegerish(min)) expect_true(testIntegerish(max)) expect_false(testIntegerish(min-1)) expect_false(testIntegerish(max+1)) expect_false(testIntegerish(min-.1)) expect_false(testIntegerish(max+.1)) expect_false(testIntegerish(NA, any.missing = FALSE)) expect_false(testIntegerish(NA, all.missing = FALSE)) expect_error(assertIntegerish(x, tol=0), "integerish") }) test_that("bounds of vectors with only missings are not checked", { expect_true(checkInteger(NA, lower = 1)) expect_true(checkInteger(NA_character_, upper = 10)) expect_fail_all(Integerish, 0, lower = 1L) expect_fail_all(Integerish, 100, upper = 10L) }) test_that("isIntegerish internal function", { expect_true(isIntegerish(1)) expect_true(isIntegerish(1.)) expect_false(isIntegerish(1.1)) }) test_that("sorted works", { expect_true(checkIntegerish(1:3, sorted = TRUE)) expect_true(grepl("sorted", checkIntegerish(3:1, sorted = TRUE), fixed = TRUE)) }) checkmate/tests/testthat/test_checkDataFrame.R0000644000176200001440000000660513154206710021212 0ustar liggesuserscontext("checkDataFrame") test_that("checkDataFrame", { myobj = iris expect_succ_all(DataFrame, myobj) myobj = TRUE expect_fail_all(DataFrame, myobj) expect_true(testDataFrame(data.frame())) expect_false(testDataFrame(NULL)) expect_true(testDataFrame(data.frame(1))) expect_true(testDataFrame(iris)) expect_false(testDataFrame(list(1))) x = iris expect_true(testDataFrame(x, types = c("numeric", "factor"))) expect_false(testDataFrame(x, types = c("integer", "factor"))) expect_false(testDataFrame(x, types = c("numeric", "character"))) expect_true(testDataFrame(data.frame(), types = "NULL")) expect_true(testDataFrame(data.frame(), types = "numeric")) expect_error(assertDataFrame(1), "data.frame") expect_error(assertDataFrame(x, types = "numeric"), "types: numeric") # check nrow and ncol constraints expect_true(testDataFrame(x, nrows = 150L, ncols = 5L)) expect_false(testDataFrame(x, nrows = 150L, ncols = 7L)) expect_true(testDataFrame(x, min.rows = 2L, min.cols = 4L)) expect_false(testDataFrame(x, min.rows = 151L, min.cols = 4L)) expect_false(testDataFrame(x, min.rows = 1L, min.cols = 6L)) }) test_that("checkDataFrame name checking works", { df = data.frame(x = 1:2, y = 1:2) names(df) = c("x", "x") expect_identical(assertDataFrame(df), df) expect_error(assertDataFrame(df, col.names = "unnamed"), "unnamed") names(df) = c("x", "") expect_error(assertDataFrame(df, col.names = "named"), "named") names(df) = c("x", "x") expect_identical(assertDataFrame(df, col.names = "named"), df) expect_error(assertDataFrame(df, col.names = "unique"), "uniquely") expect_error(assertDataFrame(df, col.names = "strict"), "uniquely") expect_error(assertDataFrame(df, col.names = "foo"), "unnamed") names(df) = c("x", "1") expect_identical(assertDataFrame(df, col.names = "named"), df) expect_identical(assertDataFrame(df, col.names = "unique"), df) expect_error(assertDataFrame(df, col.names = "strict"), "naming conventions") rownames(df) = letters[1:2] expect_succ_all(DataFrame, df, row.names = "strict") expect_succ_all(DataFrame, df, row.names = "unique") expect_succ_all(DataFrame, df, row.names = "named") expect_fail_all(DataFrame, df, row.names = "unnamed") rownames(df) = NULL expect_fail_all(DataFrame, df, row.names = "unnamed") # no names defaults to as.character(seq_row(x)) expect_succ_all(DataFrame, df, row.names = "named") expect_succ_all(DataFrame, df, row.names = "unique") expect_fail_all(DataFrame, df, row.names = "strict") }) test_that("dimension checks work for empty frames", { x = iris[, -c(1:5)] expect_true(testDataFrame(x, min.rows = 5)) expect_true(testDataFrame(x, nrows = 150)) expect_false(testDataFrame(x, min.rows = 151)) expect_false(testDataFrame(x, nrows = 1)) x = iris[-c(1:150), ] expect_true(testDataFrame(x, min.cols = 1)) expect_true(testDataFrame(x, ncols = 5)) expect_false(testDataFrame(x, min.cols = 6)) expect_false(testDataFrame(x, ncols = 1)) }) test_that("missing values are detected", { x = data.frame(a = 1:2, b = c(1, 2)) expect_true(testDataFrame(x, any.missing = FALSE)) expect_true(testDataFrame(x, all.missing = FALSE)) x$b[1] = NA expect_false(testDataFrame(x, any.missing = FALSE)) expect_true(testDataFrame(x, all.missing = FALSE)) x$b[2] = NA expect_false(testDataFrame(x, any.missing = FALSE)) expect_false(testDataFrame(x, all.missing = FALSE)) }) checkmate/tests/testthat/test_checkFunction.R0000644000176200001440000000317612762012005021147 0ustar liggesuserscontext("checkFunction") test_that("checkFunction", { myobj = mean expect_succ_all(Function, myobj) myobj = TRUE expect_fail_all(Function, myobj) myfun = function(x, y, ...) x + y expect_false(testFunction(NULL)) expect_true(testFunction(identity)) expect_true(testFunction(myfun)) expect_false(testFunction("myfun")) expect_false(testFunction("myfun")) expect_true(testFunction(myfun, args = "x")) expect_true(testFunction(myfun, args = "...")) expect_true(testFunction(myfun, args = "x", ordered=TRUE)) expect_true(testFunction(myfun, args = "y")) expect_true(testFunction(myfun, args = c("x", "y"))) expect_true(testFunction(myfun, args = c("x", "y", "..."))) expect_true(testFunction(myfun, args = c("y", "x"))) expect_true(testFunction(myfun, args = c("x", "y"), ordered=TRUE)) expect_false(testFunction(myfun, args = "z")) expect_false(testFunction(myfun, args = c("y"), ordered=TRUE)) expect_false(testFunction(myfun, args = c("y", "x"), ordered=TRUE)) expect_true(testFunction(myfun, nargs = 2)) expect_true(testFunction(myfun, args = "x", nargs = 2)) expect_true(testFunction(function() 1, nargs = 0)) expect_true(testFunction(function(...) 1, nargs = 0)) expect_false(testFunction(function(...) 1, nargs = 1)) expect_error(assertFunction(fff), "not found") expect_error(assertFunction(myfun, "z"), "formal arguments") expect_error(assertFunction(myfun, "y", ordered=TRUE), "first formal arguments") expect_false(testFunction(function(x) x^2, args = character(0))) expect_true(testFunction(function() x^2, args = character(0))) expect_error(assertFunction(letters), "character") }) checkmate/tests/testthat/test_bit.R0000644000176200001440000000205713162404132017140 0ustar liggesuserscontext("checkBit") test_that("checkBit", { skip_if_not_physically_installed("bit") expect_false(testBit(FALSE)) expect_true("bit" %in% loadedNamespaces()) xl = c(TRUE, FALSE) xb = bit::as.bit(xl) expect_succ_all(Bit, xb) expect_fail_all(Bit, xl) expect_true(checkBit(xb, len = 2)) expect_true(checkBit(xb, min.len = 2)) expect_true(checkBit(xb, max.len = 2)) expect_true(checkBit(xb, min.0 = 1)) expect_true(checkBit(xb, min.1 = 1)) expect_error(assertBit(xb, len = 1), regexp = "length") expect_error(assertBit(xb, min.len = 3), regexp = ">=") expect_error(assertBit(xb, max.len = 1), regexp = "<=") expect_error(assertBit(xb, min.0 = 2), regexp = "'0'") expect_error(assertBit(xb, min.1 = 2), regexp = "'1'") expect_error(assertBit(xb, min.1 = 2), regexp = "has 1") expect_error(checkBit(xb, len = NA), "missing") expect_error(checkBit(xb, min.len = NA), "missing") expect_error(checkBit(xb, max.len = NA), "missing") expect_error(checkBit(xb, min.0 = -1), ">=") expect_error(checkBit(xb, min.1 = NA), "missing") }) checkmate/tests/testthat/test_checkList.R0000644000176200001440000000200112762037177020300 0ustar liggesuserscontext("checkList") test_that("checkList", { myobj = list(1, 2, 3) expect_succ_all(List, myobj) myobj = TRUE expect_fail_all(List, myobj) expect_true(testList(list())) expect_false(testList(NULL)) expect_true(testList(list(1))) expect_false(testList(iris)) x = as.list(iris) expect_true(testList(x, types = c("numeric", "factor"))) expect_false(testList(x, types = c("integer", "factor"))) expect_false(testList(x, types = c("numeric", "character"))) expect_true(testList(x, types = c("vector", "factor"))) expect_true(testList(list(NULL), types = "NULL")) expect_true(testList(list(), types = "numeric")) expect_false(testList(list(TRUE), types = "numeric")) expect_error(assertList(x, types = "numeric"), "types: numeric") expect_error(assertList(x, len = 33), "Must have length 33") expect_true(testList(list(), names = "named")) x = 1:3 class(x) = "foo" x = list(x, 1:3) expect_true(testList(x, types = c("foo", "integerish"))) expect_error(assertList(1), "list") }) checkmate/tests/testthat/test_checkEnvironment.R0000644000176200001440000000127112762012005021660 0ustar liggesuserscontext("checkEnvironment") test_that("checkEnvironment", { myobj = new.env() expect_succ_all(Environment, myobj) myobj = list() expect_fail_all(Environment, myobj) ee = new.env(parent = emptyenv()) ee$yyy = 1 ee$zzz = 1 expect_false(testEnvironment(NULL)) expect_false(testEnvironment(list())) expect_true(testEnvironment(ee)) expect_false(testEnvironment(ee, contains = "xxx")) expect_true(testEnvironment(ee, contains = "yyy")) expect_true(testEnvironment(ee, contains = c("yyy", "zzz"))) expect_error(assertEnvironment(list()), "environment") expect_error(assertEnvironment(ee, "xxx"), "with name") expect_error(assertEnvironment(letters), "character") }) checkmate/tests/testthat/test_checkOS.R0000644000176200001440000000123313160423672017704 0ustar liggesuserscontext("checkOS") test_that("checkOS", { expect_succ_all(OS, c("linux", "mac", "windows", "solaris")) }) test_that("checkOS linux", { skip_on_os("windows") skip_on_os("solaris") skip_on_os("mac") expect_succ_all(OS, "linux", lc = "os") expect_error(assertOS("windows"), "windows") }) test_that("checkOS mac", { skip_on_os("windows") skip_on_os("solaris") skip_on_os("linux") expect_succ_all(OS, "mac", lc = "os") expect_error(assertOS("windows"), "windows") }) test_that("checkOS win", { skip_on_os("mac") skip_on_os("solaris") skip_on_os("linux") expect_succ_all(OS, "windows", lc = "os") expect_error(assertOS("mac"), "mac") }) checkmate/tests/testthat/test_deparse.R0000644000176200001440000000034212762012005017777 0ustar liggesuserscontext("deparse") test_that("deparse", { f = function(num, na.ok) { assertNumber(num) qassert(na.ok, "B1") } expect_true(f(1, TRUE)) expect_error(f(NULL, TRUE), "num") expect_error(f(1, NULL), "na.ok") }) checkmate/tests/test-all.R0000755000176200001440000000005212762012005015203 0ustar liggesuserslibrary(testthat) test_check("checkmate") checkmate/src/0000755000176200001440000000000013173633435012775 5ustar liggesuserscheckmate/src/which_first.c0000644000176200001440000000275213173633436015461 0ustar liggesusers#include "which_first.h" static inline SEXP named_return(R_xlen_t ind, SEXP names) { if (isNull(names)) return ScalarInteger(ind + 1); SEXP res; PROTECT(res = ScalarInteger(ind + 1)); setAttrib(res, R_NamesSymbol, ScalarString(STRING_ELT(names, ind))); UNPROTECT(1); return res; } SEXP attribute_hidden c_which_first(SEXP x, SEXP use_names) { if (!isLogical(x)) error("Argument 'x' must be logical"); if (!isLogical(use_names) || length(use_names) != 1) error("Argument 'use.names' must be a flag"); const R_xlen_t n = xlength(x); int *xp = LOGICAL(x); for (R_xlen_t i = 0; i < n; i++) { if (xp[i] != NA_LOGICAL && xp[i]) { if (LOGICAL(use_names)[0]) return named_return(i, getAttrib(x, R_NamesSymbol)); else return ScalarInteger(i+1); } } return allocVector(INTSXP, 0); } SEXP attribute_hidden c_which_last(SEXP x, SEXP use_names) { if (!isLogical(x)) error("Argument 'x' must be logical"); if (!isLogical(use_names) || xlength(use_names) != 1) error("Argument 'use.names' must be a flag"); int *xp = LOGICAL(x); for (R_xlen_t i = xlength(x) - 1; i >= 0; i--) { if (xp[i] != NA_LOGICAL && xp[i]) { if (LOGICAL(use_names)[0]) return named_return(i, getAttrib(x, R_NamesSymbol)); else return ScalarInteger(i+1); } } return allocVector(INTSXP, 0); } checkmate/src/any_infinite.h0000644000176200001440000000036313173633436015625 0ustar liggesusers#ifndef CHECKMATE_ANY_INFINITE_H_ #define CHECKMATE_ANY_INFINITE_H_ #define USE_RINTERNALS #include #include #include Rboolean any_infinite(SEXP); SEXP attribute_hidden c_any_infinite(SEXP); #endif checkmate/src/helper.h0000644000176200001440000000122413173633436014425 0ustar liggesusers#ifndef CHECKMATE_HELPER_H_ #define CHECKMATE_HELPER_H_ #define USE_RINTERNALS #include #include #include Rboolean attribute_hidden isStrictlyNumeric(SEXP); Rboolean attribute_hidden isAtomicVector(SEXP); Rboolean attribute_hidden isRList(SEXP); R_len_t attribute_hidden get_ncols(SEXP); R_len_t attribute_hidden get_nrows(SEXP); double attribute_hidden asNumber(SEXP, const char *); const char attribute_hidden * asString(SEXP, const char *); R_len_t attribute_hidden asCount(SEXP, const char *); R_xlen_t attribute_hidden asLength(SEXP, const char *); Rboolean attribute_hidden asFlag(SEXP, const char *); #endif checkmate/src/guess_type.h0000644000176200001440000000035713173633436015343 0ustar liggesusers#ifndef CHECKMATE_GUESS_TYPE_H_ #define CHECKMATE_GUESS_TYPE_H_ #define USE_RINTERNALS #include #include #include const char * guess_type(SEXP); SEXP attribute_hidden c_guess_type(SEXP); #endif checkmate/src/helper.c0000644000176200001440000000761013173633436014425 0ustar liggesusers#include #include "helper.h" #include "any_missing.h" #include "is_integerish.h" #include "guess_type.h" Rboolean attribute_hidden isStrictlyNumeric(SEXP x) { switch(TYPEOF(x)) { case REALSXP: return TRUE; case INTSXP: return !inherits(x, "factor"); } return FALSE; } Rboolean attribute_hidden isAtomicVector(SEXP x) { if (!isVectorAtomic(x)) return FALSE; return isNull(getAttrib(x, R_DimSymbol)); } /* Checks for a regular list, i.e. not a data frame, not NULL */ Rboolean attribute_hidden isRList(SEXP x) { if (TYPEOF(x) == VECSXP) { SEXP cl = getAttrib(x, R_ClassSymbol); const R_len_t n = length(cl); for (R_len_t i = 0; i < n; i++) { if (strcmp(CHAR(STRING_ELT(cl, i)), "data.frame") == 0) return FALSE; } return TRUE; } return FALSE; } /* ncols and nrows is bugged for data frames: * (a) data.frames are treated like lists and thus you get length() back * (b) reports wrong dimension for zero-column data frames * Here are our own wrappers * */ R_len_t attribute_hidden get_nrows(SEXP x) { if (isFrame(x)) return length(getAttrib(x, R_RowNamesSymbol)); SEXP dim = getAttrib(x, R_DimSymbol); return (dim == R_NilValue) ? length(x) : INTEGER(dim)[0]; } R_len_t attribute_hidden get_ncols(SEXP x) { if (isFrame(x)) return length(x); SEXP dim = getAttrib(x, R_DimSymbol); return (length(dim) >= 2) ? INTEGER(dim)[1] : 1; } double attribute_hidden asNumber(SEXP x, const char *vname) { if (!isNumeric(x)) error("Argument '%s' must be a number, but is %s", vname, guess_type(x)); if (xlength(x) != 1) error("Argument '%s' must have length 1, but has length %i", vname, xlength(x)); double xd = asReal(x); if (ISNAN(xd)) error("Argument '%s' may not be missing", vname); return xd; } const char attribute_hidden * asString(SEXP x, const char *vname) { if (!isString(x) || xlength(x) != 1) error("Argument '%s' must be a string, but is %s", vname, guess_type(x)); if (any_missing_string(x)) error("Argument '%s' may not be missing", vname); return CHAR(STRING_ELT(x, 0)); } R_len_t attribute_hidden asCount(SEXP x, const char *vname) { if (length(x) != 1) error("Argument '%x' must have length 1", vname); if (!isIntegerish(x, INTEGERISH_DEFAULT_TOL, FALSE)) error("Argument '%s' must be numeric and close to an integer", vname); int xi = asInteger(x); if (xi == NA_INTEGER) error("Argument '%s' may not be missing", vname); if (xi < 0) error("Argument '%s' must be >= 0", vname); return xi; } R_xlen_t attribute_hidden asLength(SEXP x, const char *vname) { if (length(x) != 1) error("Argument '%x' must have length 1", vname); switch(TYPEOF(x)) { case INTSXP:; int xi = INTEGER(x)[0]; if (xi == NA_INTEGER) error("Argument '%s' may not be missing", vname); if (xi < 0) error("Argument '%s' must be >= 0", vname); return (R_xlen_t) xi; case REALSXP:; double xr = REAL(x)[0]; if (xr == NA_REAL) error("Argument '%s' may not be missing", vname); if (xr < 0) error("Argument '%s' must be >= 0", vname); if (fabs(xr - nearbyint(xr)) >= INTEGERISH_DEFAULT_TOL) error("Argument '%s' is not close to an integer", vname); return (R_xlen_t) xr; } error("Argument '%s' must be a length, but is %s", vname, guess_type(x)); } Rboolean attribute_hidden asFlag(SEXP x, const char *vname) { if (!isLogical(x) || xlength(x) != 1) error("Argument '%s' must be a flag, but is %s", vname, guess_type(x)); Rboolean xb = LOGICAL(x)[0]; if (xb == NA_LOGICAL) error("Argument '%s' may not be missing", vname); return xb; } checkmate/src/is_integerish.h0000644000176200001440000000047613173633436016012 0ustar liggesusers#ifndef CHECKMATE_IS_INTEGERISH_H_ #define CHECKMATE_IS_INTEGERISH_H_ #define USE_RINTERNALS #include #include #include #define INTEGERISH_DEFAULT_TOL sqrt(DOUBLE_EPS) Rboolean isIntegerish(SEXP, double, Rboolean); SEXP attribute_hidden c_is_integerish(SEXP, SEXP); #endif checkmate/src/any_nan.c0000644000176200001440000000177313173633436014575 0ustar liggesusers#include "any_nan.h" static Rboolean any_nan_double(SEXP x) { const double * xp = REAL(x); const double * const xe = xp + xlength(x); for (; xp != xe; xp++) { if (R_IsNaN(*xp)) return TRUE; } return FALSE; } static Rboolean any_nan_complex(SEXP x) { const Rcomplex * xp = COMPLEX(x); const Rcomplex * const xe = xp + xlength(x); for (; xp != xe; xp++) { if (R_IsNaN((*xp).r) || R_IsNaN((*xp).i)) return TRUE; } return FALSE; } static Rboolean any_nan_list(SEXP x) { const R_xlen_t nx = xlength(x); for (R_xlen_t i = 0; i < nx; i++) { if (any_nan(VECTOR_ELT(x, i))) return TRUE; } return FALSE; } Rboolean any_nan(SEXP x) { switch(TYPEOF(x)) { case REALSXP: return any_nan_double(x); case CPLXSXP: return any_nan_complex(x); case VECSXP: return any_nan_list(x); } return FALSE; } SEXP attribute_hidden c_any_nan(SEXP x) { return ScalarLogical(any_nan(x)); } checkmate/src/any_infinite.c0000644000176200001440000000221013173633436015611 0ustar liggesusers#include "any_infinite.h" static Rboolean any_infinite_double(SEXP x) { const double * xp = REAL(x); const double * const xe = xp + xlength(x); for (; xp != xe; xp++) { if (*xp == R_PosInf || *xp == R_NegInf) return TRUE; } return FALSE; } static Rboolean any_infinite_complex(SEXP x) { const Rcomplex * xp = COMPLEX(x); const Rcomplex * const xe = xp + xlength(x); for (; xp != xe; xp++) { if ((*xp).r == R_PosInf || (*xp).i == R_PosInf || (*xp).r == R_NegInf || (*xp).i == R_NegInf) return TRUE; } return FALSE; } static Rboolean any_infinite_list(SEXP x) { const R_xlen_t nx = xlength(x); for (R_xlen_t i = 0; i < nx; i++) { if (any_infinite(VECTOR_ELT(x, i))) return TRUE; } return FALSE; } Rboolean any_infinite(SEXP x) { switch(TYPEOF(x)) { case REALSXP: return any_infinite_double(x); case CPLXSXP: return any_infinite_complex(x); case VECSXP: return any_infinite_list(x); } return FALSE; } SEXP attribute_hidden c_any_infinite(SEXP x) { return ScalarLogical(any_infinite(x)); } checkmate/src/all_nchar.h0000644000176200001440000000026413173633436015074 0ustar liggesusers#ifndef CHECKMATE_ALL_NCHAR_H_ #define CHECKMATE_ALL_NCHAR_H_ #define USE_RINTERNALS #include #include Rboolean all_nchar(SEXP, R_xlen_t, Rboolean); #endif checkmate/src/all_nchar.c0000644000176200001440000000105413173633436015065 0ustar liggesusers#include "all_nchar.h" Rboolean all_nchar(SEXP x, R_xlen_t n, Rboolean skip_na) { if (!isString(x)) { SEXP xs = PROTECT(coerceVector(x, STRSXP)); Rboolean res = all_nchar(xs, n, skip_na); UNPROTECT(1); return res; } const R_xlen_t nx = xlength(x); for (R_xlen_t i = 0; i < nx; i++) { if (STRING_ELT(x, i) == NA_STRING) { if (skip_na) continue; return FALSE; } if (xlength(STRING_ELT(x, i)) < n) { return FALSE; } } return TRUE; } checkmate/src/any_missing.c0000644000176200001440000000657513173633436015477 0ustar liggesusers#include "any_missing.h" Rboolean attribute_hidden any_missing_logical(SEXP x) { const int * xp = LOGICAL(x); const int * const xe = xp + xlength(x); for (; xp != xe; xp++) { if (*xp == NA_LOGICAL) return TRUE; } return FALSE; } Rboolean attribute_hidden any_missing_integer(SEXP x) { const int * xp = INTEGER(x); const int * const xe = xp + xlength(x); for (; xp != xe; xp++) { if (*xp == NA_INTEGER) return TRUE; } return FALSE; } Rboolean attribute_hidden any_missing_integerish(SEXP x) { switch(TYPEOF(x)) { case LGLSXP: return any_missing_logical(x); case INTSXP: return any_missing_integer(x); case REALSXP: return any_missing_double(x); default: error("Error in any_missing_integerish: x is not logical or numeric"); } } Rboolean attribute_hidden any_missing_double(SEXP x) { const double * xp = REAL(x); const double * const xe = xp + xlength(x); for (; xp != xe; xp++) { if (ISNAN(*xp)) return TRUE; } return FALSE; } Rboolean attribute_hidden any_missing_numeric(SEXP x) { switch(TYPEOF(x)) { case INTSXP: return any_missing_integer(x); case REALSXP: return any_missing_double(x); default: error("Error in any_missing_numeric: x is not integer or double"); } } Rboolean attribute_hidden any_missing_complex(SEXP x) { const Rcomplex * xp = COMPLEX(x); const Rcomplex * const xe = xp + xlength(x); for (; xp != xe; xp++) { if (ISNAN((*xp).r) || ISNAN((*xp).i)) return TRUE; } return FALSE; } Rboolean attribute_hidden any_missing_string(SEXP x) { const R_xlen_t nx = xlength(x); for (R_xlen_t i = 0; i < nx; i++) { if (STRING_ELT(x, i) == NA_STRING) return TRUE; } return FALSE; } Rboolean attribute_hidden any_missing_atomic(SEXP x) { switch(TYPEOF(x)) { case LGLSXP: return any_missing_logical(x); case INTSXP: return any_missing_integer(x); case REALSXP: return any_missing_double(x); case CPLXSXP: return any_missing_complex(x); case STRSXP: return any_missing_string(x); default: return FALSE; } } Rboolean attribute_hidden any_missing_list(SEXP x) { const R_xlen_t nx = xlength(x); for (R_xlen_t i = 0; i < nx; i++) { if (isNull(VECTOR_ELT(x, i))) return TRUE; } return FALSE; } Rboolean attribute_hidden any_missing_matrix(SEXP x) { return any_missing_atomic(x); } Rboolean attribute_hidden any_missing_frame(SEXP x) { const R_xlen_t nc = xlength(x); for (R_xlen_t i = 0; i < nc; i++) { if (any_missing_atomic(VECTOR_ELT(x, i))) return TRUE; } return FALSE; } Rboolean any_missing(SEXP x) { switch(TYPEOF(x)) { case LGLSXP: return any_missing_logical(x); case INTSXP: return any_missing_integer(x); case REALSXP: return any_missing_double(x); case CPLXSXP: return any_missing_complex(x); case STRSXP: return any_missing_string(x); case NILSXP: return FALSE; case VECSXP: return isFrame(x) ? any_missing_frame(x) : any_missing_list(x); case RAWSXP: return FALSE; default: error("Object of type '%s' not supported", type2char(TYPEOF(x))); } } SEXP attribute_hidden c_any_missing(SEXP x) { return ScalarLogical(any_missing(x)); } checkmate/src/any_nan.h0000644000176200001440000000033713173633436014575 0ustar liggesusers#ifndef CHECKMATE_ANY_NAN_H_ #define CHECKMATE_ANY_NAN_H_ #define USE_RINTERNALS #include #include #include Rboolean any_nan(SEXP); SEXP attribute_hidden c_any_nan(SEXP); #endif checkmate/src/guess_type.c0000644000176200001440000000175713173633436015343 0ustar liggesusers#include "guess_type.h" #include const char * guess_type(SEXP x) { SEXP attr = getAttrib(x, R_ClassSymbol); if (!isNull(attr)) { const R_len_t n = length(attr); if (n == 1) return CHAR(STRING_ELT(attr, 0)); /* Constuct name using [class1]/[class2]/... */ static char buf[512]; const char * tmp = CHAR(STRING_ELT(attr, 0)); strncpy(buf, tmp, 512); R_len_t written = strlen(tmp); for (R_len_t i = 1; i < n; i++) { tmp = CHAR(STRING_ELT(attr, i)); if (strlen(tmp) > 512 - written - 1) break; written += snprintf(buf + written, 512 - written, "/%s", tmp); } return buf; } attr = getAttrib(x, R_DimSymbol); if (!isNull(attr) && isVectorAtomic(x)) return length(attr) == 2 ? "matrix" : "array"; return type2char(TYPEOF(x)); } SEXP attribute_hidden c_guess_type(SEXP x) { return ScalarString(mkChar(guess_type(x))); } checkmate/src/which_first.h0000644000176200001440000000034713173633436015464 0ustar liggesusers#ifndef CHECKMATE_WHICH_FIRST_H_ #define CHECKMATE_WHICH_FIRST_H_ #define USE_RINTERNALS #include #include #include SEXP c_which_first(SEXP, SEXP); SEXP c_which_last(SEXP, SEXP); #endif checkmate/src/all_missing.h0000644000176200001440000000114413173633436015450 0ustar liggesusers#ifndef CHECKMATE_ALL_MISSING_H_ #define CHECKMATE_ALL_MISSING_H_ #define USE_RINTERNALS #include #include #include Rboolean all_missing_logical(SEXP); Rboolean all_missing_integer(SEXP); Rboolean all_missing_integerish(SEXP); Rboolean all_missing_double(SEXP); Rboolean all_missing_numeric(SEXP); Rboolean all_missing_complex(SEXP); Rboolean all_missing_string(SEXP); Rboolean all_missing_atomic(SEXP); Rboolean all_missing_list(SEXP); Rboolean all_missing_matrix(SEXP); Rboolean all_missing_frame(SEXP); Rboolean all_missing(SEXP); SEXP c_all_missing(SEXP); #endif checkmate/src/checks.c0000644000176200001440000006472013173633436014413 0ustar liggesusers#include #include #include "checks.h" #include "is_integerish.h" #include "any_missing.h" #include "any_infinite.h" #include "all_missing.h" #include "all_nchar.h" #include "helper.h" #include "guess_type.h" static char msg[255] = ""; #define HANDLE_TYPE(expr, expected) \ if (!(expr)) { \ snprintf(msg, 255, "Must be of type '%s', not '%s'", expected, guess_type(x)); \ return ScalarString(mkChar(msg)); \ } #define HANDLE_TYPE_NULL(expr, expected, null_ok) \ if (isNull((x))) { \ if (asFlag((null_ok), "null.ok")) \ return ScalarLogical(TRUE); \ snprintf(msg, 255, "Must be of type '%s', not 'NULL'", expected); \ return ScalarString(mkChar(msg)); \ } else { \ if (!(expr)) { \ snprintf(msg, 255, "Must be of type '%s'%s, not '%s'", expected, asFlag(null_ok, "null_ok") ? " (or 'NULL')" : "", guess_type(x)); \ return ScalarString(mkChar(msg)); \ } \ } #define HANDLE_NA(x, na_ok) \ if (is_scalar_na((x))) { \ if (asFlag((na_ok), "na.ok")) \ return ScalarLogical(TRUE); \ return result("May not be NA"); \ }; #define ASSERT_TRUE(x) if (!(x)) return ScalarString(mkChar(msg)); #define ASSERT_TRUE_UNPROTECT(x, p) \ Rboolean TMP = (x); \ UNPROTECT((p)); \ if (!TMP) return ScalarString(mkChar(msg)); /*********************************************************************************************************************/ /* Some helpers */ /*********************************************************************************************************************/ static Rboolean message(const char *fmt, ...) { va_list vargs; va_start(vargs, fmt); vsnprintf(msg, 255, fmt, vargs); va_end(vargs); return FALSE; } static SEXP result(const char *fmt, ...) { va_list vargs; va_start(vargs, fmt); vsnprintf(msg, 255, fmt, vargs); va_end(vargs); return ScalarString(mkChar(msg)); } static Rboolean is_posixct(SEXP x) { return isReal(x) && inherits(x, "POSIXct"); } static void fmt_posixct(char * out, SEXP x) { SEXP call = PROTECT(allocVector(LANGSXP, 2)); SETCAR(call, install("format.POSIXct")); SETCADR(call, x); SEXP result = PROTECT(eval(call, R_GlobalEnv)); strncpy(out, CHAR(STRING_ELT(result, 0)), 255); UNPROTECT(2); } static Rboolean check_bounds(SEXP x, SEXP lower, SEXP upper) { double tmp = asNumber(lower, "lower"); if (R_FINITE(tmp)) { if (isReal(x)) { const double *xp = REAL(x); const double * const xend = xp + xlength(x); for (; xp != xend; xp++) { if (!ISNAN(*xp) && *xp < tmp) return message("All elements must be >= %g", tmp); } } else if (isInteger(x)) { const int *xp = INTEGER(x); const int * const xend = xp + xlength(x); for (; xp != xend; xp++) { if (*xp != NA_INTEGER && *xp < tmp) return message("All elements must be >= %g", tmp); } } } tmp = asNumber(upper, "upper"); if (R_FINITE(tmp)) { if (isReal(x)) { const double *xp = REAL(x); const double * const xend = xp + xlength(x); for (; xp != xend; xp++) { if (!ISNAN(*xp) && *xp > tmp) return message("All elements must be <= %g", tmp); } } else if (isInteger(x)) { const int *xp = INTEGER(x); const int * const xend = xp + xlength(x); for (; xp != xend; xp++) { if (*xp != NA_INTEGER && *xp > tmp) return message("All elements must be <= %g", tmp); } } } return TRUE; } Rboolean check_posix_bounds(SEXP x, SEXP lower, SEXP upper) { if (isNull(lower) && isNull(upper)) return TRUE; SEXP tz = PROTECT(getAttrib(x, install("tzone"))); const Rboolean null_tz = isNull(tz); if (!isNull(lower)) { if (!is_posixct(lower) || length(lower) != 1) error("Argument 'lower' must be provided as single POSIXct time"); SEXP lower_tz = PROTECT(getAttrib(lower, install("tzone"))); if (null_tz != isNull(lower_tz) || (!null_tz && !isNull(lower_tz) && strcmp(CHAR(STRING_ELT(tz, 0)), CHAR(STRING_ELT(lower_tz, 0))) != 0)) { UNPROTECT(2); return message("Timezones of 'x' and 'lower' must match"); } const double tmp = REAL(lower)[0]; const double *xp = REAL(x); const double * const xend = xp + xlength(x); for (; xp != xend; xp++) { if (!ISNAN(*xp) && *xp < tmp) { char fmt[255]; fmt_posixct(fmt, lower); UNPROTECT(2); return message("All times must be >= %s", fmt); } } UNPROTECT(1); } if (!isNull(upper)) { if (!is_posixct(upper) || length(upper) != 1) error("Argument 'upper' must be provided as single POSIXct time"); SEXP upper_tz = PROTECT(getAttrib(upper, install("tzone"))); if (null_tz != isNull(upper_tz) || (!null_tz && !isNull(upper_tz) && strcmp(CHAR(STRING_ELT(tz, 0)), CHAR(STRING_ELT(upper_tz, 0))) != 0)) { UNPROTECT(2); return message("Timezones of 'x' and 'upper' must match"); } const double tmp = REAL(upper)[0]; const double *xp = REAL(x); const double * const xend = xp + xlength(x); for (; xp != xend; xp++) { if (!ISNAN(*xp) && *xp > tmp) { char fmt[255]; fmt_posixct(fmt, upper); UNPROTECT(2); return message("All times must be <= %s", fmt); } } UNPROTECT(1); } UNPROTECT(1); return TRUE; } static Rboolean check_strict_names(SEXP x) { const R_xlen_t nx = xlength(x); const char *str; for (R_xlen_t i = 0; i < nx; i++) { str = CHAR(STRING_ELT(x, i)); while (*str == '.') str++; if (!isalpha(*str)) return FALSE; for (; *str != '\0'; str++) { if (!isalnum(*str) && *str != '.' && *str != '_') return FALSE; } } return TRUE; } static Rboolean check_names(SEXP nn, const char * type, const char * what) { typedef enum { T_UNNAMED, T_NAMED, T_UNIQUE, T_STRICT } name_t; name_t checks = T_UNNAMED; if (strcmp(type, "unnamed") == 0) return isNull(nn) ? TRUE : message("%s must be unnamed, but has names", what); if (strcmp(type, "named") == 0) { checks = T_NAMED; } else if (strcmp(type, "unique") == 0) { checks = T_UNIQUE; } else if (strcmp(type, "strict") == 0) { checks = T_STRICT; } else { error("Unknown type '%s' to specify check for names. Supported are 'unnamed', 'named', 'unique' and 'strict'.", type); } if (isNull(nn) || any_missing_string(nn) || !all_nchar(nn, 1, FALSE)) return message("%s must be named", what); if (checks >= T_UNIQUE) { if (any_duplicated(nn, FALSE) != 0) return message("%s must be uniquely named", what); if (checks >= T_STRICT && !check_strict_names(nn)) { return message("%s must be named according to R's variable naming conventions and may not contain special characters", what); } } return TRUE; } static Rboolean check_named(SEXP x, const char * type, const char * what) { SEXP nn = PROTECT(getAttrib(x, R_NamesSymbol)); Rboolean res = check_names(nn, type, what); UNPROTECT(1); return res; } static Rboolean check_vector_len(SEXP x, SEXP len, SEXP min_len, SEXP max_len) { if (!isNull(len)) { R_xlen_t n = asLength(len, "len"); if (xlength(x) != n) return message("Must have length %g, but has length %g", (double)n, (double)xlength(x)); } if (!isNull(min_len)) { R_xlen_t n = asLength(min_len, "min.len"); if (xlength(x) < n) return message("Must have length >= %g, but has length %g", (double)n, (double)xlength(x)); } if (!isNull(max_len)) { R_xlen_t n = asLength(max_len, "max.len"); if (xlength(x) > n) return message("Must have length <= %g, but has length %g", (double)n, (double)xlength(x)); } return TRUE; } static Rboolean check_vector_missings(SEXP x, SEXP any_missing, SEXP all_missing) { if (!asFlag(any_missing, "any.missing") && any_missing_atomic(x)) return message("Contains missing values"); if (!asFlag(all_missing, "all.missing") && all_missing_atomic(x)) return message("Contains only missing values"); return TRUE; } static Rboolean check_vector_unique(SEXP x, SEXP unique) { if (asFlag(unique, "unique") && any_duplicated(x, FALSE) > 0) return message("Contains duplicated values"); return TRUE; } static Rboolean check_vector_names(SEXP x, SEXP names) { if (!isNull(names) && xlength(x) > 0) return check_named(x, asString(names, "names"), "Vector"); return TRUE; } static Rboolean check_vector_finite(SEXP x, SEXP finite) { if (asFlag(finite, "finite") && any_infinite(x)) return message("Must be finite"); return TRUE; } static Rboolean check_matrix_dims(SEXP x, SEXP min_rows, SEXP min_cols, SEXP rows, SEXP cols) { if (!isNull(min_rows) || !isNull(rows)) { R_len_t xrows = get_nrows(x); if (!isNull(min_rows)) { R_len_t cmp = asLength(min_rows, "min.rows"); if (xrows < cmp) return message("Must have at least %i rows, but has %i rows", cmp, xrows); } if (!isNull(rows)) { R_len_t cmp = asLength(rows, "rows"); if (xrows != cmp) return message("Must have exactly %i rows, but has %i rows", cmp, xrows); } } if (!isNull(min_cols) || !isNull(cols)) { R_len_t xcols = get_ncols(x); if (!isNull(min_cols)) { R_len_t cmp = asLength(min_cols, "min.cols"); if (xcols < cmp) return message("Must have at least %i cols, but has %i cols", cmp, xcols); } if (!isNull(cols)) { R_len_t cmp = asCount(cols, "cols"); if (xcols != cmp) return message("Must have exactly %i cols, but has %i cols", cmp, xcols); } } return TRUE; } static Rboolean check_storage(SEXP x, SEXP mode) { if (!isNull(mode)) { const char * const storage = asString(mode, "mode"); if (strcmp(storage, "logical") == 0) { if (!isLogical(x)) return message("Must store logicals"); } else if (strcmp(storage, "integer") == 0) { if (!isInteger(x)) return message("Must store integers"); } else if (strcmp(storage, "double") == 0) { if (!isReal(x)) return message("Must store doubles"); } else if (strcmp(storage, "integerish") == 0) { if (!isIntegerish(x, INTEGERISH_DEFAULT_TOL, FALSE)) return message("Must store integerish values"); } else if (strcmp(storage, "numeric") == 0) { if (!isStrictlyNumeric(x)) return message("Must store numerics"); } else if (strcmp(storage, "complex") == 0) { if (!isComplex(x)) return message("Must store complexs"); } else if (strcmp(storage, "character") == 0) { if (!isString(x)) return message("Must store characters"); } else if (strcmp(storage, "list") == 0) { if (!isRList(x)) return message("Must store a list"); } else if (strcmp(storage, "atomic") == 0) { if (!isVectorAtomic(x)) return message("Must be atomic"); } else { error("Invalid argument 'mode'. Must be one of 'logical', 'integer', 'integerish', 'double', 'numeric', 'complex', 'character', 'list' or 'atomic'"); } } return TRUE; } static inline Rboolean is_scalar_na(SEXP x) { if (xlength(x) == 1) { switch(TYPEOF(x)) { case LGLSXP: return (LOGICAL(x)[0] == NA_LOGICAL); case INTSXP: return (INTEGER(x)[0] == NA_INTEGER); case REALSXP: return ISNAN(REAL(x)[0]); case STRSXP: return (STRING_ELT(x, 0) == NA_STRING); } } return FALSE; } static Rboolean is_sorted_integer(SEXP x) { R_xlen_t i = 0; const int * const xi = INTEGER(x); const R_xlen_t n = xlength(x); while(xi[i] == NA_INTEGER) { i++; if (i == n) return TRUE; } for (R_xlen_t j = i + 1; j < n; j++) { if (xi[j] != NA_INTEGER) { if (xi[i] > xi[j]) return FALSE; i = j; } } return TRUE; } static Rboolean is_sorted_double(SEXP x) { R_xlen_t i = 0; const double * const xr = REAL(x); const R_xlen_t n = xlength(x); while(xr[i] == NA_REAL) { i++; if (i == n) return TRUE; } for (R_xlen_t j = i + 1; j < n; j++) { if (xr[j] != NA_REAL) { if (xr[i] > xr[j]) return FALSE; i = j; } } return TRUE; } static Rboolean check_vector_sorted(SEXP x, SEXP sorted) { if (asFlag(sorted, "sorted") && xlength(x) > 1) { Rboolean ok; switch(TYPEOF(x)) { case INTSXP: ok = is_sorted_integer(x); break; case REALSXP: ok = is_sorted_double(x); break; default: error("Checking for sorted vector only possible for integer and double"); } if (!ok) return message("Must be sorted"); } return TRUE; } /*********************************************************************************************************************/ /* Exported check functions */ /*********************************************************************************************************************/ SEXP attribute_hidden c_check_character(SEXP x, SEXP min_chars, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP names, SEXP null_ok) { HANDLE_TYPE_NULL(isString(x) || all_missing_atomic(x), "character", null_ok); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); if (!isNull(min_chars)) { R_xlen_t n = asCount(min_chars, "min.chars"); if (n > 0 && !all_nchar(x, n, TRUE)) return result("All elements must have at least %i characters", n); } ASSERT_TRUE(check_vector_unique(x, unique)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_complex(SEXP x, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP names, SEXP null_ok) { HANDLE_TYPE_NULL(isComplex(x) || all_missing_atomic(x), "complex", null_ok); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_vector_unique(x, unique)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_dataframe(SEXP x, SEXP any_missing, SEXP all_missing, SEXP min_rows, SEXP min_cols, SEXP rows, SEXP cols, SEXP row_names, SEXP col_names, SEXP null_ok) { HANDLE_TYPE_NULL(isFrame(x), "data.frame", null_ok); ASSERT_TRUE(check_matrix_dims(x, min_rows, min_cols, rows, cols)); if (!isNull(row_names)) { SEXP nn = PROTECT(getAttrib(x, install("row.names"))); if (isInteger(nn)) nn = coerceVector(nn, STRSXP); ASSERT_TRUE_UNPROTECT(check_names(nn, asString(row_names, "row.names"), "Rows"), 1); } if (!isNull(col_names)) ASSERT_TRUE(check_named(x, asString(col_names, "col.names"), "Columns")); if (!asFlag(any_missing, "any.missing") && any_missing_frame(x)) return result("Contains missing values"); if (!asFlag(all_missing, "all.missing") && all_missing_frame(x)) return result("Contains only missing values"); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_factor(SEXP x, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP names, SEXP null_ok) { HANDLE_TYPE_NULL(isFactor(x) || all_missing_atomic(x), "factor", null_ok); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_vector_unique(x, unique)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_integer(SEXP x, SEXP lower, SEXP upper, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP sorted, SEXP names, SEXP null_ok) { HANDLE_TYPE_NULL(isInteger(x) || all_missing_atomic(x), "integer", null_ok); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_bounds(x, lower, upper)); ASSERT_TRUE(check_vector_unique(x, unique)); ASSERT_TRUE(check_vector_sorted(x, sorted)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_integerish(SEXP x, SEXP tol, SEXP lower, SEXP upper, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP sorted, SEXP names, SEXP null_ok) { double dtol = asNumber(tol, "tol"); HANDLE_TYPE_NULL(isIntegerish(x, dtol, FALSE) || all_missing_atomic(x), "integerish", null_ok); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_bounds(x, lower, upper)); ASSERT_TRUE(check_vector_unique(x, unique)); ASSERT_TRUE(check_vector_sorted(x, sorted)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_list(SEXP x, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP names, SEXP null_ok) { HANDLE_TYPE_NULL(isRList(x), "list", null_ok) ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_vector_unique(x, unique)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_logical(SEXP x, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP names, SEXP null_ok) { HANDLE_TYPE_NULL(isLogical(x) || all_missing_atomic(x), "logical", null_ok); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_vector_unique(x, unique)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_matrix(SEXP x, SEXP mode, SEXP any_missing, SEXP all_missing, SEXP min_rows, SEXP min_cols, SEXP rows, SEXP cols, SEXP row_names, SEXP col_names, SEXP null_ok) { HANDLE_TYPE_NULL(isMatrix(x), "matrix", null_ok); ASSERT_TRUE(check_storage(x, mode)); ASSERT_TRUE(check_matrix_dims(x, min_rows, min_cols, rows, cols)); if (!isNull(row_names) && xlength(x) > 0) { SEXP nn = PROTECT(getAttrib(x, R_DimNamesSymbol)); if (!isNull(nn)) nn = VECTOR_ELT(nn, 0); ASSERT_TRUE_UNPROTECT(check_names(nn, asString(row_names, "row.names"), "Rows"), 1); } if (!isNull(col_names) && xlength(x) > 0) { SEXP nn = PROTECT(getAttrib(x, R_DimNamesSymbol)); if (!isNull(nn)) nn = VECTOR_ELT(nn, 1); ASSERT_TRUE_UNPROTECT(check_names(nn, asString(col_names, "col.names"), "Columns"), 1); } ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_array(SEXP x, SEXP mode, SEXP any_missing, SEXP d, SEXP min_d, SEXP max_d, SEXP null_ok) { HANDLE_TYPE_NULL(isArray(x), "array", null_ok); ASSERT_TRUE(check_storage(x, mode)); if (!asFlag(any_missing, "any.missing") && any_missing_atomic(x)) return result("Contains missing values"); R_len_t ndim = length(getAttrib(x, R_DimSymbol)); if (!isNull(d)) { R_len_t di = asCount(d, "d"); if (ndim != di) return result("Must be a %i-d array, but has dimension %i", di, ndim); } if (!isNull(min_d)) { R_len_t di = asCount(min_d, "min.d"); if (ndim < di) return result("Must have >=%i dimensions, but has dimension %i", di, ndim); } if (!isNull(max_d)) { R_len_t di = asCount(max_d, "max.d"); if (ndim > di) return result("Must have <=%i dimensions, but has dimension %i", di, ndim); } return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_named(SEXP x, SEXP type) { if (!isNull(type) && xlength(x) > 0) ASSERT_TRUE(check_named(x, asString(type, "type"), "Object")); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_names(SEXP x, SEXP type) { if (!(isString(x) || isNull(x))) return result("Must be a character vector of names"); ASSERT_TRUE(check_names(x, asString(type, "type"), "Names")); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_numeric(SEXP x, SEXP lower, SEXP upper, SEXP finite, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP sorted, SEXP names, SEXP null_ok) { HANDLE_TYPE_NULL(isStrictlyNumeric(x) || all_missing_atomic(x), "numeric", null_ok); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_bounds(x, lower, upper)); ASSERT_TRUE(check_vector_finite(x, finite)); ASSERT_TRUE(check_vector_unique(x, unique)); ASSERT_TRUE(check_vector_sorted(x, sorted)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_vector(SEXP x, SEXP strict, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP names, SEXP null_ok) { HANDLE_TYPE_NULL(isVector(x), "vector", null_ok); if (asFlag(strict, "strict")) { SEXP attr = ATTRIB(x); HANDLE_TYPE( (length(attr) == 0 || (TAG(attr) == R_NamesSymbol)) && CDR(attr) == R_NilValue, "vector"); } ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_vector_unique(x, unique)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_atomic(SEXP x, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP names) { HANDLE_TYPE(isNull(x) || isVectorAtomic(x), "atomic"); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_vector_unique(x, unique)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_atomic_vector(SEXP x, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP names) { HANDLE_TYPE(isAtomicVector(x), "atomic vector"); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_vector_unique(x, unique)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_flag(SEXP x, SEXP na_ok, SEXP null_ok) { HANDLE_NA(x, na_ok); HANDLE_TYPE_NULL(isLogical(x), "logical flag", null_ok); if (xlength(x) != 1) return result("Must have length 1"); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_count(SEXP x, SEXP na_ok, SEXP positive, SEXP tol, SEXP null_ok) { HANDLE_NA(x, na_ok) double dtol = asNumber(tol, "tol"); HANDLE_TYPE_NULL(isIntegerish(x, dtol, FALSE), "count", null_ok); if (xlength(x) != 1) return result("Must have length 1"); const int pos = (int) asFlag(positive, "positive"); if (asInteger(x) < pos) return result("Must be >= %i", pos); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_int(SEXP x, SEXP na_ok, SEXP lower, SEXP upper, SEXP tol, SEXP null_ok) { double dtol = asNumber(tol, "tol"); HANDLE_NA(x, na_ok); HANDLE_TYPE_NULL(isIntegerish(x, dtol, FALSE), "single integerish value", null_ok); if (xlength(x) != 1) return result("Must have length 1"); ASSERT_TRUE(check_bounds(x, lower, upper)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_number(SEXP x, SEXP na_ok, SEXP lower, SEXP upper, SEXP finite, SEXP null_ok) { HANDLE_NA(x, na_ok); HANDLE_TYPE_NULL(isStrictlyNumeric(x), "number", null_ok); if (xlength(x) != 1) return result("Must have length 1"); ASSERT_TRUE(check_vector_finite(x, finite)); ASSERT_TRUE(check_bounds(x, lower, upper)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_string(SEXP x, SEXP na_ok, SEXP min_chars, SEXP null_ok) { HANDLE_NA(x, na_ok); HANDLE_TYPE_NULL(isString(x), "string", null_ok); if (xlength(x) != 1) return result("Must have length 1"); if (!isNull(min_chars)) { R_xlen_t n = asCount(min_chars, "min.chars"); if (!all_nchar(x, n, TRUE)) return result("Must have at least %i characters", n); } return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_scalar(SEXP x, SEXP na_ok, SEXP null_ok) { HANDLE_NA(x, na_ok); HANDLE_TYPE_NULL(isVectorAtomic(x), "atomic scalar", null_ok); if (xlength(x) != 1) return result("Must have length 1"); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_posixct(SEXP x, SEXP lower, SEXP upper, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP sorted, SEXP null_ok) { HANDLE_TYPE_NULL(is_posixct(x), "POSIXct", null_ok); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_vector_unique(x, unique)); ASSERT_TRUE(check_posix_bounds(x, lower, upper)); ASSERT_TRUE(check_vector_sorted(x, sorted)); return ScalarLogical(TRUE); } #undef HANDLE_TYPE #undef HANDLE_TYPE_NULL #undef HANDLE_NA #undef ASSERT_TRUE #undef ASSERT_TRUE_UNPROTECT checkmate/src/init.c0000644000176200001440000001137513173633436014114 0ustar liggesusers#include #include #include // for NULL #include #include "qassert.h" /* .Call calls */ extern SEXP c_all_missing(SEXP); extern SEXP c_any_infinite(SEXP); extern SEXP c_any_missing(SEXP); extern SEXP c_any_nan(SEXP); extern SEXP c_check_array(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_atomic(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_atomic_vector(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_character(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_complex(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_count(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_dataframe(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_factor(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_flag(SEXP, SEXP, SEXP); extern SEXP c_check_int(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_integer(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_integerish(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_list(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_logical(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_matrix(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_named(SEXP, SEXP); extern SEXP c_check_names(SEXP, SEXP); extern SEXP c_check_number(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_numeric(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_scalar(SEXP, SEXP, SEXP); extern SEXP c_check_string(SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_vector(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_posixct(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_guess_type(SEXP); extern SEXP c_is_integerish(SEXP, SEXP); extern SEXP c_qassert(SEXP, SEXP, SEXP); extern SEXP c_qtest(SEXP, SEXP, SEXP, SEXP); extern SEXP c_which_first(SEXP, SEXP); extern SEXP c_which_last(SEXP, SEXP); static const R_CallMethodDef CallEntries[] = { {"c_all_missing", (DL_FUNC) &c_all_missing, 1}, {"c_any_infinite", (DL_FUNC) &c_any_infinite, 1}, {"c_any_missing", (DL_FUNC) &c_any_missing, 1}, {"c_any_nan", (DL_FUNC) &c_any_nan, 1}, {"c_check_array", (DL_FUNC) &c_check_array, 7}, {"c_check_atomic", (DL_FUNC) &c_check_atomic, 8}, {"c_check_atomic_vector", (DL_FUNC) &c_check_atomic_vector, 8}, {"c_check_character", (DL_FUNC) &c_check_character, 10}, {"c_check_complex", (DL_FUNC) &c_check_complex, 9}, {"c_check_count", (DL_FUNC) &c_check_count, 5}, {"c_check_dataframe", (DL_FUNC) &c_check_dataframe, 10}, {"c_check_factor", (DL_FUNC) &c_check_factor, 9}, {"c_check_flag", (DL_FUNC) &c_check_flag, 3}, {"c_check_int", (DL_FUNC) &c_check_int, 6}, {"c_check_integer", (DL_FUNC) &c_check_integer, 12}, {"c_check_integerish", (DL_FUNC) &c_check_integerish, 13}, {"c_check_list", (DL_FUNC) &c_check_list, 9}, {"c_check_logical", (DL_FUNC) &c_check_logical, 9}, {"c_check_matrix", (DL_FUNC) &c_check_matrix, 11}, {"c_check_named", (DL_FUNC) &c_check_named, 2}, {"c_check_names", (DL_FUNC) &c_check_names, 2}, {"c_check_number", (DL_FUNC) &c_check_number, 6}, {"c_check_numeric", (DL_FUNC) &c_check_numeric, 13}, {"c_check_scalar", (DL_FUNC) &c_check_scalar, 3}, {"c_check_string", (DL_FUNC) &c_check_string, 4}, {"c_check_vector", (DL_FUNC) &c_check_vector, 10}, {"c_check_posixct", (DL_FUNC) &c_check_posixct, 11}, {"c_guess_type", (DL_FUNC) &c_guess_type, 1}, {"c_is_integerish", (DL_FUNC) &c_is_integerish, 2}, {"c_qassert", (DL_FUNC) &c_qassert, 3}, {"c_qtest", (DL_FUNC) &c_qtest, 4}, {"c_which_first", (DL_FUNC) &c_which_first, 2}, {"c_which_last", (DL_FUNC) &c_which_last, 2}, {NULL, NULL, 0} }; void R_init_checkmate(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); R_RegisterCCallable("checkmate", "qtest", (DL_FUNC) &qtest); R_RegisterCCallable("checkmate", "qassert", (DL_FUNC) &qassert); } checkmate/src/any_missing.h0000644000176200001440000000146013173633436015470 0ustar liggesusers#ifndef CHECKMATE_ANY_MISSING_H_ #define CHECKMATE_ANY_MISSING_H_ #define USE_RINTERNALS #include #include #include Rboolean attribute_hidden any_missing_logical(SEXP); Rboolean attribute_hidden any_missing_integer(SEXP); Rboolean attribute_hidden any_missing_integerish(SEXP); Rboolean attribute_hidden any_missing_double(SEXP); Rboolean attribute_hidden any_missing_numeric(SEXP); Rboolean attribute_hidden any_missing_complex(SEXP); Rboolean attribute_hidden any_missing_string(SEXP); Rboolean attribute_hidden any_missing_atomic(SEXP); Rboolean attribute_hidden any_missing_list(SEXP); Rboolean attribute_hidden any_missing_matrix(SEXP); Rboolean attribute_hidden any_missing_frame(SEXP); Rboolean any_missing(SEXP); SEXP attribute_hidden c_any_missing(SEXP); #endif checkmate/src/qassert.c0000644000176200001440000004563513173633436014641 0ustar liggesusers#include "qassert.h" #include "helper.h" #include "guess_type.h" #include "any_missing.h" #include "is_integerish.h" typedef enum { CL_LOGICAL, CL_INTEGER, CL_INTEGERISH, CL_NUMERIC, CL_DOUBLE, CL_STRING, CL_FACTOR, CL_LIST, CL_COMPLEX, CL_ATOMIC, CL_ATOMIC_VECTOR, CL_MATRIX, CL_DATAFRAME, CL_FUNCTION, CL_ENVIRONMENT, CL_NULL, CL_NONE } class_t; static const char * CLSTR[] = { "logical", "integer", "integerish", "numeric", "double", "string", "factor", "list", "complex", "atomic", "atomic vector", "matrix", "data frame", "function", "environment", "NULL" }; typedef enum { LT, LE, EQ, GE, GT, NE, NONE } cmp_t; static const char * CMPSTR[] = { "<", "<=", "==", ">=", ">", "!=" }; typedef Rboolean(*dd_cmp)(double, double); typedef Rboolean(*ll_cmp)(R_xlen_t, R_xlen_t); typedef struct { dd_cmp fun; double cmp; cmp_t op; } bound_t; typedef struct { struct { Rboolean(*fun)(SEXP); class_t name; } class; struct { Rboolean(*fun)(SEXP); } missing; struct { ll_cmp fun; R_xlen_t cmp; cmp_t op; } len; bound_t lower; bound_t upper; } checker_t; typedef struct { Rboolean ok; char msg[255]; } msg_t; static inline Rboolean ii_eq(const R_xlen_t x, const R_xlen_t y) { return x == y; } static inline Rboolean ii_lt(const R_xlen_t x, const R_xlen_t y) { return x < y; } static inline Rboolean ii_gt(const R_xlen_t x, const R_xlen_t y) { return x > y; } static inline Rboolean ii_le(const R_xlen_t x, const R_xlen_t y) { return x <= y; } static inline Rboolean ii_ge(const R_xlen_t x, const R_xlen_t y) { return x >= y; } static inline Rboolean dd_lt(const double x, const double y) { return x < y; } static inline Rboolean dd_gt(const double x, const double y) { return x > y; } static inline Rboolean dd_le(const double x, const double y) { return x <= y; } static inline Rboolean dd_ge(const double x, const double y) { return x >= y; } static inline Rboolean dd_ne(const double x, const double y) { return x != y; } static inline Rboolean is_class_logical(SEXP x) { return isLogical(x); } static inline Rboolean is_class_integer(SEXP x) { return isInteger(x); } static inline Rboolean is_class_integerish(SEXP x) { return isIntegerish(x, INTEGERISH_DEFAULT_TOL, TRUE); } static inline Rboolean is_class_double(SEXP x) { return isReal(x); } static inline Rboolean is_class_numeric(SEXP x) { return isStrictlyNumeric(x); } static inline Rboolean is_class_complex(SEXP x) { return isComplex(x); } static inline Rboolean is_class_string(SEXP x) { return isString(x); } static inline Rboolean is_class_factor(SEXP x) { return isFactor(x); } static inline Rboolean is_class_atomic(SEXP x) { return isNull(x) || isVectorAtomic(x); } static inline Rboolean is_class_atomic_vector(SEXP x) { return isAtomicVector(x); } static inline Rboolean is_class_list(SEXP x) { return isRList(x); } static inline Rboolean is_class_matrix(SEXP x) { return isMatrix(x); } static inline Rboolean is_class_frame(SEXP x) { return isFrame(x); } static inline Rboolean is_class_environment(SEXP x) { return isEnvironment(x); } static inline Rboolean is_class_null(SEXP x) { return isNull(x); } static const msg_t MSGT = { .ok = TRUE }; static const msg_t MSGF = { .ok = FALSE }; static msg_t message(const char *fmt, ...) { msg_t msg = { .ok = FALSE }; va_list vargs; va_start(vargs, fmt); vsnprintf(msg.msg, 255, fmt, vargs); va_end(vargs); return msg; } /*********************************************************************************************************************/ /* Some helper functions */ /*********************************************************************************************************************/ static msg_t check_bound(SEXP x, const bound_t bound) { if (isReal(x)) { const double *xp = REAL(x); const double * const xend = xp + xlength(x); for (; xp != xend; xp++) { if (!ISNAN(*xp) && !bound.fun(*xp, bound.cmp)) { if (bound.cmp == R_PosInf) return message("All elements must be %s Inf", CMPSTR[bound.op]); if (bound.cmp == R_NegInf) return message("All elements must be %s -Inf", CMPSTR[bound.op]); return message("All elements must be %s %g", CMPSTR[bound.op], bound.cmp); } } } else if (isInteger(x)) { const int *xp = INTEGER(x); const int * const xend = xp + xlength(x); for (; xp != xend; xp++) { if (*xp != NA_INTEGER && !bound.fun((double) *xp, bound.cmp)) return message("All elements must be %s %g", CMPSTR[bound.op], bound.cmp); } } else if (isString(x)) { const R_xlen_t nx = xlength(x); double nchar; for (R_xlen_t i = 0; i < nx; i++) { nchar = STRING_ELT(x, i) == NA_STRING ? 0. : (double)length(STRING_ELT(x, i)); if (!bound.fun(nchar, bound.cmp)) return message("All elements must have %s %g chars", CMPSTR[bound.op], bound.cmp); } } else if (isFactor(x)) { return check_bound(getAttrib(x, R_LevelsSymbol), bound); } else { error("Bound checks only possible for numeric variables, strings and factors, not %s", guess_type(x)); } return MSGT; } /*********************************************************************************************************************/ /* First step: Parse string and built checker_t object */ /*********************************************************************************************************************/ static int parse_class(checker_t *checker, const char *rule) { checker->missing.fun = NULL; switch(rule[0]) { case 'B': checker->missing.fun = &any_missing_logical; case 'b': checker->class.fun = &is_class_logical; checker->class.name = CL_LOGICAL; break; case 'I': checker->missing.fun = &any_missing_integer; case 'i': checker->class.fun = &is_class_integer; checker->class.name = CL_INTEGER; break; case 'X': checker->missing.fun = &any_missing_integerish; case 'x': checker->class.fun = &is_class_integerish; checker->class.name = CL_INTEGERISH; break; case 'N': checker->missing.fun = &any_missing_numeric; case 'n': checker->class.fun = &is_class_numeric; checker->class.name = CL_NUMERIC; break; case 'R': checker->missing.fun = &any_missing_double; case 'r': checker->class.fun = &is_class_double; checker->class.name = CL_DOUBLE; break; case 'S': checker->missing.fun = &any_missing_string; case 's': checker->class.fun = &is_class_string; checker->class.name = CL_STRING; break; case 'F': checker->missing.fun = &any_missing_integer; case 'f': checker->class.fun = &is_class_factor; checker->class.name = CL_FACTOR; break; case 'L': checker->missing.fun = &any_missing_list; case 'l': checker->class.fun = &is_class_list; checker->class.name = CL_LIST; break; case 'C': checker->missing.fun = &any_missing_complex; case 'c': checker->class.fun = &is_class_complex; checker->class.name = CL_COMPLEX; break; case 'A': checker->missing.fun = &any_missing_atomic; case 'a': checker->class.fun = &is_class_atomic; checker->class.name = CL_ATOMIC; break; case 'V': checker->missing.fun = &any_missing_atomic; case 'v': checker->class.fun = &is_class_atomic_vector; checker->class.name = CL_ATOMIC_VECTOR; break; case 'M': checker->missing.fun = &any_missing_matrix; case 'm': checker->class.fun = &is_class_matrix; checker->class.name = CL_MATRIX; break; case 'D': checker->missing.fun = &any_missing_frame; case 'd': checker->class.fun = &is_class_frame; checker->class.name = CL_DATAFRAME; break; case 'e': checker->class.fun = &is_class_environment; checker->class.name = CL_ENVIRONMENT; break; case '0': checker->class.fun = &is_class_null; checker->class.name = CL_NULL; break; case '*': checker->class.fun = NULL; checker->class.name = CL_NONE; break; default: error("Unknown class identifier '%c'", rule[0]); } return 1; } static int parse_length(checker_t *checker, const char *rule) { switch(rule[0]) { case '*': checker->len.fun = NULL; return 1; case '?': checker->len.fun = &ii_le; checker->len.cmp = 1; checker->len.op = LE; return 1; case '+': checker->len.fun = &ii_ge; checker->len.cmp = 1; checker->len.op = GE; return 1; case '(': case '[': case '\0': checker->len.fun = NULL; checker->len.op = NONE; return 0; } const char *start = rule; switch(rule[0]) { case '=': checker->len.fun = &ii_eq; checker->len.op = EQ; start += 1 + (rule[1] == '='); break; case '<': if (rule[1] == '=') { checker->len.fun = &ii_le; checker->len.op = LE; start += 2; } else { checker->len.fun = &ii_lt; checker->len.op = LE; start += 1; } break; case '>': if (rule[1] == '=') { checker->len.fun = &ii_ge; checker->len.op = GE; start += 2; } else { checker->len.fun = &ii_gt; checker->len.op = GT; start += 1; } break; default: checker->len.fun = &ii_eq; checker->len.op = EQ; break; } char *end; long int cmp = strtol(start, &end, 10); if (start == end) error("Invalid length definition: %s", rule); if (cmp >= INT_MAX) error("Cannot handle length >= %i", INT_MAX); if (cmp < 0) error("Cannot check for negative length"); checker->len.cmp = (int)cmp; return end - rule; } static int parse_bounds(checker_t *checker, const char *rule) { switch(rule[0]) { case '\0': checker->lower.fun = NULL; checker->upper.fun = NULL; return 0; case '(': checker->lower.fun = &dd_gt; checker->lower.op = GT; break; case '[': checker->lower.fun = &dd_ge; checker->lower.op = GE; break; default: error("Invalid bound definition, missing opening '(' or '[': %s", rule); } char *end; const char *start = rule + 1; double cmp = strtod(start, &end); if (start == end) { if (checker->lower.op == GT) { checker->lower.fun = &dd_ne; checker->lower.cmp = R_NegInf; checker->lower.op = NE; } else { checker->lower.fun = NULL; } } else { checker->lower.cmp = cmp; } switch(*end) { case ',' : start = end + 1; case ')' : case ']' : break; default : error("Invalid bound definition, error parsing lower bound, missing separator ',' or missing closing ')' or ']': %s", rule); } cmp = strtod(start, &end); if (*end == ')') { if (start == end) { checker->upper.fun = &dd_ne; checker->upper.cmp = R_PosInf; checker->upper.op = NE; } else { checker->upper.fun = &dd_lt; checker->upper.cmp = cmp; checker->upper.op = LT; } } else if (*end == ']') { if (start == end) { checker->upper.fun = NULL; } else { checker->upper.fun = &dd_le; checker->upper.cmp = cmp; checker->upper.op = LE; } } else { error("Invalid bound definition, error parsing upper bound or missing closing ')' or ']': %s", rule); } return end - rule + 1; } static void parse_rule(checker_t *checker, const char *rule) { const R_len_t nchars = strlen(rule); if (nchars == 0) error("Empty rule"); rule += parse_class(checker, rule); rule += parse_length(checker, rule); rule += parse_bounds(checker, rule); if (rule[0] == '\0') return; error("Additional chars found in rule!"); } /*********************************************************************************************************************/ /* Second step: check SEXP using a checker_t object */ /*********************************************************************************************************************/ static msg_t check_rule(SEXP x, const checker_t *checker, const Rboolean err_msg) { if (checker->class.fun != NULL && !checker->class.fun(x)) { return err_msg ? message("Must be of class '%s', not '%s'", CLSTR[checker->class.name], guess_type(x)) : MSGF; } if (checker->missing.fun != NULL && checker->missing.fun(x)) { return err_msg ? message("May not contain missing values") : MSGF; } if (checker->len.fun != NULL && !checker->len.fun(xlength(x), checker->len.cmp)) { return err_msg ? message("Must be of length %s %i, but has length %g", CMPSTR[checker->len.op], checker->len.cmp, (double)xlength(x)) : MSGF; } if (checker->lower.fun != NULL) { msg_t msg = check_bound(x, checker->lower); if (!msg.ok) return msg; } if (checker->upper.fun != NULL) { msg_t msg = check_bound(x, checker->upper); if (!msg.ok) return msg; } return MSGT; } /*********************************************************************************************************************/ /* qassert stuff */ /*********************************************************************************************************************/ static inline R_len_t qassert1(SEXP x, const checker_t *checker, msg_t *result, const R_len_t nrules) { for (R_len_t i = 0; i < nrules; i++) { result[i] = check_rule(x, &checker[i], result[i].ok); if (result[i].ok) return 0; } return 1; } static inline R_len_t qassert_list(SEXP x, const checker_t *checker, msg_t *result, const R_len_t nrules) { if (!isNewList(x) || isNull(x)) error("Argument 'x' must be a list or data.frame"); const R_len_t nx = xlength(x); for (R_xlen_t i = 0; i < nx; i++) { if (qassert1(VECTOR_ELT(x, i), checker, result, nrules) != 0) return i + 1; } return 0; } /* exported for other packages */ SEXP qassert(SEXP x, const char *rule, const char *name) { checker_t checker; parse_rule(&checker, rule); msg_t result = check_rule(x, &checker, TRUE); if (!result.ok) error("Variable '%s': %s", name, result.msg); return x; } SEXP attribute_hidden c_qassert(SEXP x, SEXP rules, SEXP recursive) { const Rboolean nrules = length(rules); R_len_t failed; if (!isString(rules)) error("Argument 'rules' must be a string"); if (nrules == 0) return ScalarLogical(TRUE); msg_t result[nrules]; checker_t checker[nrules]; SEXP tmp; for (R_len_t i = 0; i < nrules; i++) { tmp = STRING_ELT(rules, i); if (tmp == NA_STRING) error("Rule may not be NA"); parse_rule(&checker[i], CHAR(tmp)); result[i].ok = TRUE; } if (LOGICAL(recursive)[0]) { failed = qassert_list(x, checker, result, nrules); } else { failed = qassert1(x, checker, result, nrules); } if (failed == 0) return ScalarLogical(TRUE); SEXP msgs = PROTECT(allocVector(STRSXP, nrules)); SEXP pos = PROTECT(ScalarInteger(failed)); setAttrib(msgs, install("pos"), pos); for (R_len_t i = 0; i < nrules; i++) SET_STRING_ELT(msgs, i, mkChar(result[i].msg)); UNPROTECT(2); return msgs; } /*********************************************************************************************************************/ /* qtest stuff */ /*********************************************************************************************************************/ static inline Rboolean qtest1(SEXP x, const checker_t *checker, const R_len_t nrules) { msg_t result; for (R_len_t i = 0; i < nrules; i++) { result = check_rule(x, &checker[i], FALSE); if (result.ok) return TRUE; } return FALSE; } static inline Rboolean qtest_list(SEXP x, const checker_t *checker, const R_len_t nrules, R_len_t depth) { if (!isNewList(x) || isNull(x)) error("Argument 'x' must be a list or data.frame"); const R_len_t nx = xlength(x); if (depth > 1) { for (R_xlen_t i = 0; i < nx; i++) { if (isRList(VECTOR_ELT(x, i))) { if (!qtest_list(VECTOR_ELT(x, i), checker, nrules, depth - 1)) return FALSE; } else { if (!qtest1(VECTOR_ELT(x, i), checker, nrules)) return FALSE; } } } else { for (R_xlen_t i = 0; i < nx; i++) { if (!qtest1(VECTOR_ELT(x, i), checker, nrules)) return FALSE; } } return TRUE; } /* exported for other packages */ Rboolean qtest(SEXP x, const char *rule) { checker_t checker; parse_rule(&checker, rule); return qtest1(x, &checker, 1); } SEXP attribute_hidden c_qtest(SEXP x, SEXP rules, SEXP recursive, SEXP depth) { const R_len_t nrules = length(rules); if (!isString(rules)) error("Argument 'rules' must be a string"); if (nrules == 0) return ScalarLogical(TRUE); checker_t checker[nrules]; SEXP tmp; for (R_len_t i = 0; i < nrules; i++) { tmp = STRING_ELT(rules, i); if (tmp == NA_STRING) error("Rule may not be NA"); parse_rule(&checker[i], CHAR(STRING_ELT(rules, i))); } if (LOGICAL(recursive)[0]) return ScalarLogical(qtest_list(x, checker, nrules, asCount(depth, "depth"))); return ScalarLogical(qtest1(x, checker, nrules)); } checkmate/src/is_integerish.c0000644000176200001440000000235413173633436016002 0ustar liggesusers#include "is_integerish.h" #include #include static inline Rboolean is_unconvertible(const double x, const double tol) { return (!ISNAN(x) && (x <= INT_MIN || x > INT_MAX || fabs(x - nearbyint(x)) >= tol)); } static Rboolean is_integerish_double(SEXP x, const double tol) { const double *xr = REAL(x); const double * const xend = xr + xlength(x); for (; xr != xend; xr++) { if (is_unconvertible(*xr, tol)) return FALSE; } return TRUE; } static Rboolean is_integerish_complex(SEXP x, const double tol) { const Rcomplex * xc = COMPLEX(x); const Rcomplex * const xe = xc + xlength(x); for (; xc != xe; xc++) { if (fabs((*xc).i) >= tol || is_unconvertible((*xc).r, tol)) return FALSE; } return TRUE; } Rboolean isIntegerish(SEXP x, const double tol, Rboolean logicals_ok) { switch(TYPEOF(x)) { case LGLSXP: return logicals_ok; case INTSXP: return TRUE; case REALSXP: return is_integerish_double(x, tol); case CPLXSXP: return is_integerish_complex(x, tol); } return FALSE; } SEXP attribute_hidden c_is_integerish(SEXP x, SEXP tolerance) { return ScalarLogical(isIntegerish(x, REAL(tolerance)[0], FALSE)); } checkmate/src/all_missing.c0000644000176200001440000000530313173633436015444 0ustar liggesusers#include "all_missing.h" Rboolean attribute_hidden all_missing_logical(SEXP x) { const int * xp = LOGICAL(x); const int * const xe = xp + xlength(x); for (; xp != xe; xp++) { if (*xp != NA_LOGICAL) return FALSE; } return TRUE; } Rboolean attribute_hidden all_missing_integer(SEXP x) { const int * xp = INTEGER(x); const int * const xe = xp + xlength(x); for (; xp != xe; xp++) { if (*xp != NA_INTEGER) return FALSE; } return TRUE; } Rboolean attribute_hidden all_missing_double(SEXP x) { const double * xp = REAL(x); const double * const xe = xp + xlength(x); for (; xp != xe; xp++) { if (!ISNAN(*xp)) return FALSE; } return TRUE; } Rboolean attribute_hidden all_missing_complex(SEXP x) { const Rcomplex * xp = COMPLEX(x); const Rcomplex * const xe = xp + xlength(x); for (; xp != xe; xp++) { if (!ISNAN((*xp).r) || !ISNAN((*xp).i)) return FALSE; } return TRUE; } Rboolean attribute_hidden all_missing_string(SEXP x) { const R_xlen_t nx = xlength(x); for (R_xlen_t i = 0; i < nx; i++) { if (STRING_ELT(x, i) != NA_STRING) return FALSE; } return TRUE; } Rboolean attribute_hidden all_missing_atomic(SEXP x) { switch(TYPEOF(x)) { case LGLSXP: return all_missing_logical(x); case INTSXP: return all_missing_integer(x); case REALSXP: return all_missing_double(x); case CPLXSXP: return all_missing_complex(x); case STRSXP: return all_missing_string(x); default: return FALSE; } } Rboolean attribute_hidden all_missing_list(SEXP x) { const R_xlen_t nx = xlength(x); for (R_xlen_t i = 0; i < nx; i++) { if (!isNull(VECTOR_ELT(x, i))) return FALSE; } return TRUE; } Rboolean attribute_hidden all_missing_frame(SEXP x) { const R_xlen_t nc = xlength(x); for (R_xlen_t i = 0; i < nc; i++) { if (all_missing_atomic(VECTOR_ELT(x, i))) return TRUE; } return FALSE; } Rboolean attribute_hidden all_missing(SEXP x) { switch(TYPEOF(x)) { case LGLSXP: return all_missing_logical(x); case INTSXP: return all_missing_integer(x); case REALSXP: return all_missing_double(x); case CPLXSXP: return all_missing_complex(x); case STRSXP: return all_missing_string(x); case NILSXP: return FALSE; case VECSXP: return isFrame(x) ? all_missing_frame(x) : all_missing_list(x); case RAWSXP: return FALSE; default: error("Object of type '%s' not supported", type2char(TYPEOF(x))); } } SEXP attribute_hidden c_all_missing(SEXP x) { return ScalarLogical(all_missing(x)); } checkmate/src/checks.h0000644000176200001440000000374313173633436014416 0ustar liggesusers#ifndef CHECKMATE_CHECKS_H_ #define CHECKMATE_CHECKS_H_ #define USE_RINTERNALS #include #include #include SEXP attribute_hidden c_check_array(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_atomic(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_atomic_vector(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_character(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_complex(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_dataframe(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_factor(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_integer(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_integerish(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_list(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_logical(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_matrix(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_named(SEXP, SEXP); SEXP attribute_hidden c_check_names(SEXP, SEXP); SEXP attribute_hidden c_check_numeric(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_vector(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_count(SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_flag(SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_int(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_number(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_scalar(SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_string(SEXP, SEXP, SEXP, SEXP); #endif checkmate/src/qassert.h0000644000176200001440000000053613173633436014635 0ustar liggesusers#ifndef CHECKMATE_QASSERT_H_ #define CHECKMATE_QASSERT_H_ #define USE_RINTERNALS #include #include #include SEXP attribute_hidden c_qassert(SEXP, SEXP, SEXP); SEXP attribute_hidden c_qtest(SEXP, SEXP, SEXP, SEXP); SEXP qassert(SEXP, const char *, const char *); Rboolean qtest(SEXP, const char *); #endif checkmate/NAMESPACE0000644000176200001440000002043013167637071013427 0ustar liggesusers# Generated by roxygen2: do not edit by hand S3method(print,AssertCollection) export("%??%") export(allMissing) export(anyInfinite) export(anyMissing) export(anyNaN) export(asCount) export(asInt) export(asInteger) export(assert) export(assertAccess) export(assertArray) export(assertAtomic) export(assertAtomicVector) export(assertBit) export(assertCharacter) export(assertChoice) export(assertClass) export(assertComplex) export(assertCount) export(assertDataFrame) export(assertDataTable) export(assertDate) export(assertDirectory) export(assertDirectoryExists) export(assertEnvironment) export(assertFALSE) export(assertFactor) export(assertFile) export(assertFileExists) export(assertFlag) export(assertFunction) export(assertInt) export(assertInteger) export(assertIntegerish) export(assertList) export(assertLogical) export(assertMatrix) export(assertNamed) export(assertNames) export(assertNull) export(assertNumber) export(assertNumeric) export(assertOS) export(assertPOSIXct) export(assertPathForOutput) export(assertR6) export(assertScalar) export(assertScalarNA) export(assertSetEqual) export(assertString) export(assertSubset) export(assertTRUE) export(assertTibble) export(assertVector) export(assert_access) export(assert_array) export(assert_atomic) export(assert_atomic_vector) export(assert_bit) export(assert_character) export(assert_choice) export(assert_class) export(assert_complex) export(assert_count) export(assert_data_frame) export(assert_data_table) export(assert_date) export(assert_directory) export(assert_directory_exists) export(assert_environment) export(assert_factor) export(assert_false) export(assert_file) export(assert_file_exists) export(assert_flag) export(assert_function) export(assert_int) export(assert_integer) export(assert_integerish) export(assert_list) export(assert_logical) export(assert_matrix) export(assert_named) export(assert_names) export(assert_null) export(assert_number) export(assert_numeric) export(assert_os) export(assert_path_for_output) export(assert_posixct) export(assert_r6) export(assert_scalar) export(assert_scalar_na) export(assert_set_equal) export(assert_string) export(assert_subset) export(assert_tibble) export(assert_true) export(assert_vector) export(checkAccess) export(checkArray) export(checkAtomic) export(checkAtomicVector) export(checkBit) export(checkCharacter) export(checkChoice) export(checkClass) export(checkComplex) export(checkCount) export(checkDataFrame) export(checkDataTable) export(checkDate) export(checkDirectory) export(checkDirectoryExists) export(checkEnvironment) export(checkFALSE) export(checkFactor) export(checkFile) export(checkFileExists) export(checkFlag) export(checkFunction) export(checkInt) export(checkInteger) export(checkIntegerish) export(checkList) export(checkLogical) export(checkMatrix) export(checkNamed) export(checkNames) export(checkNull) export(checkNumber) export(checkNumeric) export(checkOS) export(checkPOSIXct) export(checkPathForOutput) export(checkR6) export(checkScalar) export(checkScalarNA) export(checkSetEqual) export(checkString) export(checkSubset) export(checkTRUE) export(checkTibble) export(checkVector) export(check_access) export(check_array) export(check_atomic) export(check_atomic_vector) export(check_bit) export(check_character) export(check_choice) export(check_class) export(check_complex) export(check_count) export(check_data_frame) export(check_data_table) export(check_date) export(check_directory_exists) export(check_environment) export(check_factor) export(check_false) export(check_file_exists) export(check_flag) export(check_function) export(check_int) export(check_integer) export(check_integerish) export(check_list) export(check_logical) export(check_matrix) export(check_named) export(check_names) export(check_null) export(check_number) export(check_numeric) export(check_os) export(check_path_for_output) export(check_posixct) export(check_r6) export(check_scalar) export(check_scalar_na) export(check_set_equal) export(check_string) export(check_subset) export(check_tibble) export(check_true) export(check_vector) export(expect_access) export(expect_array) export(expect_atomic) export(expect_atomic_vector) export(expect_bit) export(expect_character) export(expect_choice) export(expect_class) export(expect_complex) export(expect_count) export(expect_data_frame) export(expect_data_table) export(expect_date) export(expect_directory) export(expect_directory_exists) export(expect_environment) export(expect_factor) export(expect_file) export(expect_file_exists) export(expect_flag) export(expect_function) export(expect_int) export(expect_integer) export(expect_integerish) export(expect_list) export(expect_logical) export(expect_matrix) export(expect_names) export(expect_number) export(expect_numeric) export(expect_os) export(expect_path_for_output) export(expect_posixct) export(expect_r6) export(expect_scalar) export(expect_scalar_na) export(expect_set_equal) export(expect_string) export(expect_subset) export(expect_tibble) export(expect_vector) export(makeAssertCollection) export(makeAssertion) export(makeAssertionFunction) export(makeExpectation) export(makeExpectationFunction) export(makeTest) export(makeTestFunction) export(matchArg) export(qassert) export(qassertr) export(qexpect) export(qexpectr) export(qtest) export(qtestr) export(reportAssertions) export(testAccess) export(testArray) export(testAtomic) export(testAtomicVector) export(testBit) export(testCharacter) export(testChoice) export(testClass) export(testComplex) export(testCount) export(testDataFrame) export(testDataTable) export(testDate) export(testDirectory) export(testDirectoryExists) export(testEnvironment) export(testFALSE) export(testFactor) export(testFile) export(testFileExists) export(testFlag) export(testFunction) export(testInt) export(testInteger) export(testIntegerish) export(testList) export(testLogical) export(testMatrix) export(testNamed) export(testNames) export(testNull) export(testNumber) export(testNumeric) export(testOS) export(testPOSIXct) export(testPathForOutput) export(testR6) export(testScalar) export(testScalarNA) export(testSetEqual) export(testString) export(testSubset) export(testTRUE) export(testTibble) export(testVector) export(test_access) export(test_array) export(test_atomic) export(test_atomic_vector) export(test_bit) export(test_character) export(test_choice) export(test_class) export(test_complex) export(test_count) export(test_data_frame) export(test_data_table) export(test_date) export(test_directory) export(test_directory_exists) export(test_environment) export(test_factor) export(test_false) export(test_file_exists) export(test_flag) export(test_function) export(test_int) export(test_integer) export(test_integerish) export(test_list) export(test_logical) export(test_matrix) export(test_named) export(test_names) export(test_null) export(test_number) export(test_numeric) export(test_os) export(test_path_for_output) export(test_posixct) export(test_r6) export(test_scalar) export(test_scalar_na) export(test_set_equal) export(test_string) export(test_subset) export(test_tibble) export(test_true) export(test_vector) export(vname) export(wf) export(wl) importFrom(utils,getFromNamespace) importFrom(utils,head) importFrom(utils,packageVersion) importFrom(utils,tail) useDynLib(checkmate,c_all_missing) useDynLib(checkmate,c_any_infinite) useDynLib(checkmate,c_any_missing) useDynLib(checkmate,c_any_nan) useDynLib(checkmate,c_check_array) useDynLib(checkmate,c_check_atomic) useDynLib(checkmate,c_check_atomic_vector) useDynLib(checkmate,c_check_character) useDynLib(checkmate,c_check_complex) useDynLib(checkmate,c_check_count) useDynLib(checkmate,c_check_dataframe) useDynLib(checkmate,c_check_factor) useDynLib(checkmate,c_check_flag) useDynLib(checkmate,c_check_int) useDynLib(checkmate,c_check_integer) useDynLib(checkmate,c_check_integerish) useDynLib(checkmate,c_check_list) useDynLib(checkmate,c_check_logical) useDynLib(checkmate,c_check_matrix) useDynLib(checkmate,c_check_named) useDynLib(checkmate,c_check_names) useDynLib(checkmate,c_check_number) useDynLib(checkmate,c_check_numeric) useDynLib(checkmate,c_check_posixct) useDynLib(checkmate,c_check_scalar) useDynLib(checkmate,c_check_string) useDynLib(checkmate,c_check_vector) useDynLib(checkmate,c_guess_type) useDynLib(checkmate,c_is_integerish) useDynLib(checkmate,c_qassert) useDynLib(checkmate,c_qtest) useDynLib(checkmate,c_which_first) useDynLib(checkmate,c_which_last) checkmate/NEWS.md0000644000176200001440000002135713167640175013316 0ustar liggesusers# Version 1.8.5 * Added `*POSIXct` to check POSIXct data-time objects in POSIXct format. * The set functions optionally support the package `fastmatch` now. * Argument `sorted = TRUE` is not passed to `ls()` anymore to support R versions prior to v3.2.0. # Version 1.8.4 * New functions to test bit vectors implemented in package `bit`. * New functions to test R6 classes implemented in package `R6`. * Always load (not attach) the respective namespace if checking for objects of type `data.table`, `tibble`, `R6` or `bit`. This ensures that all operations work as expected after the check. * `*Names` with `type="unnamed"` now works with `NULL`. * New argument `must.include` for `*Names`. * Fixed possible protection stack imbalance as reported by `rchk`. # Version 1.8.3 * New argument `sorted` (defaults to `FALSE`) for `*Integer`, `*Integerish` and `Numeric` to check for ascending order of vector elements. * New argument `null.ok` (defaults to `FALSE`) for `*Choice` and `*Class`. * `*Subset` now allows to pass empty vectors to `choices`. * Improved error message for `*Choice`. * The set family of functions is now more restrict regarding the class, e.g. they differentiate between factors and characters. * `*Character` and `*String` now ignores missing values in regular expressions and for string length checks (using argument `min.chars`). To disallow missing values, set `any.missing` or `na.ok`, respectively. * `*Date` now ignores missing values in for lower/upper bound checks. To disallow missing values, set `any.missing` to `FALSE`. Thanks to Will Beasley (@wibeasley) for the PR. * Package `microbenchmark` is no longer strictly required to build the vignette. If not installed, some output and figures will be missing though. # Version 1.8.2 * `*Matrix` and `*Array` now additionally allow to check for integerish storage type via argument "mode". * Functions `*Count`, `*Int`, `*Number`, `*Integer`, `*Integerish` and `*Numeric` do not accept logical values any more. * `checkAtomicVector` is now more restrictive and prohibits a dimension symbol. Thus, a matrix is not considered an atomic vector any more. * Dropped support for AssertCollections in convert functions (`asInt`, `asInteger` and `asCount`). * Added `checkTibble`. # Version 1.8.1 * Function `test_file` is longer exported. * `*Function` does not longer lookup functions with `match.fun`. As a result, passing functions via the string of the function name stopped working. * In `qassert` using `f` as first char in a rule now specifies factor (before: function). # Version 1.8.0 * Most functions now support the handling of default arguments encoded as `NULL` via argument `null.ok`. * Functions `*File` and `*Directory` are deprecated due to name clashes and will be removed in a future version. Please use `*FileExists` or `*DirectoryExists` instead. * New helper function `matchArg` to provide a simple an easy way for partial argument matching in combination with an AssertCollection. * Added alias functions for all check functions (`check_*`) to provide support for the underscore programming style in `assert()`. # Version 1.7.4 * Compatibility with the upcoming testthat version. * `expect_` functions now return the checked object invisibly. * Changed default of argument `.var.name` for assertions and `label` for expectations: They now default to the return value of the exported function `vname` (instead of missing which confuses some linters). * Fixed error message in convert functions: Variable name was not properly looked up by the heuristic. * Fixed a bug in `qassertr` and `qtestr` where the error message was not properly generated if multiple rules were provided. * New argument `depth` for `qtestr` to control the recursion depth while checking nested lists. # Version 1.7.3 * Added `checkDate()`. * Argument `.var.name` of assert functions now has \code{NULL} as default value (instead of missing). * Fixed a bug in `*OS` functions. * Fixed a bug in `*Directory` functions. * New argument `extension` for the `*File` family of functions. # Version 1.7.2 * Added `checkOS()`. * Argument `fixed` for `*Character` functions now accepts a string instead of a boolean value and thus can directly be used for a substring search. * New arguments `min.chars`, `pattern`, `fixed` and `ignore.case` for the `*String` family of functions. * Exported helper functions `wf` (which.first) and `wl` (which.last). * Now importing the new backports package for functions `lengths()` and `dir.exists`. # Version 1.7.1 * Fixed a segfault while checking an upper bound in qassert/qtest. * Some minor speedups # Version 1.7.0 * Added alias functions for all functions to support the underscore style, e.g. `assert_numeric` is the new alias for `assertNumeric` and `test_matrix` is the alias for `test_matrix`. * All assert functions now invisibly return the tested object instead of `TRUE` and thus can be used with magrittr pipes. * Improved speed for most functions by reducing the .Call overhead (Thanks to Hadley Wickham). * Added `*DataTable` functions to properly test primary and secondary keys of data tables. * Removed `*Percentage` family of functions. * Exported functions `makeAssertion`, `makeTest` and `makeExpectation` to assist expanding the package with user-generated checks. * Added functions `makeAssertionFunction`, `makeTestFunction` and `makeExpectationFunction` to automatically create the respective functions based on a provided check function. # Version 1.6.3 * Assertions can now be collected (via `makeAssertCollection()`) and reported (via `reportAssertions()`). * `qassert()` can now perform bound checks on strings. * The default for the parameter "ordered" of the `*SetEqual` functions is now set to FALSE, as described in the documentation. # Version 1.6.2 * Fixed a compile-time warning. * checkmate does not import `testthat` anymore in order to speed up package loading times and to keep the dependencies at a minimum. The `expect_*` family of functions can still be used, the namespace will be loaded on demand. # Version 1.6.1 * New family of functions: `expect_*` is intended to be used in combination with testthat. But note that functions `expect_null()` and `expect_named()` are not provided to avoid name clashes with testthat. * Added `qexpect()` and `qexpectr()`. * Added argument `all.missing` for checks of matricies and data frames. * Added `anyNaN()`. * Clarified documentation for `assert()` and `allMissing()`. * Fixed a bug where bound checks were performed on missing values. * Fixed a bug where missingness was not correctly detected in data frames. # Version 1.6.0 * Started to support long vectors. * Added a short vignette. * Improved documentation. * New argument "combine" for `assert()` to allow combining check functions with an AND instead of an OR. # Version 1.5.3 * Fixed a bug regarding the number of rows in zero-column data frames. * Fixed a bug where the type of lists with dimension attribute where reported as "array" or "matrix". * Family *Array: new arguments "min.d" and "max.d". * Family *Array and *Matrix: Argument "mode" now additionally accepts strings "list" and "atomic". # Version 1.5.2 * Fixed: `(assert|check|test)Character(NA_character_, min.chars = 1)` does not eval to TRUE anymore. * New arguments for `*Factor` functions: `(n|min|max).levels`. * Improved error messages for type and length checks. * Improved error messages for missing arguments. # Version 1.5.1 * Included a workaround for R's nrow and ncol to properly work with data frames. * Fixed a bug handling complex number in checks for integerish values. * Improved documentation. # Version 1.5.0 * Added `checkNames()`. * Added `checkPercentage()`. * Added `anyInfinite()`. * Fixed error messages for some dimension checks. * Fixed an error while checking numerics for finiteness. # Version 1.4 * Fixed a bug where rownames and colnames of data.frames where not retrieved correctly. * Fixed a bug in `checkVector()` (wrong order of arguments in call to C). * Filesystem access: checks for write and executable rights are now disabled on windows. # Version 1.3 * Fixed a bug where logical values passed a check for numerics in `qassert`. * Family `*SetEqual`: new argument "ordered". * `checkPathForOutput`: new argument "overwrite". # Version 1.2 * Fixed bug in checkList. * Fixed dimnames check on empty matrices and data frames. * Added `*SetEqual` functions. # Version 1.1 * Improved error messages in `assert*` functions. * New argument 'empty.ok' for `*Subset` functions. * `assert()` now returns TRUE invisibly (as documented). * Fixed handling of zero-length arguments in `checkFunction()`. * Fixed error message if duplicated values where found. * Fixed a missing check for row names in `checkMatrix()` and `checkDataFrame()`. # Version 1.0 * Initial release on CRAN. checkmate/R/0000755000176200001440000000000013171650103012374 5ustar liggesuserscheckmate/R/checkNumber.R0000644000176200001440000000230712762010266014754 0ustar liggesusers#' Check if an argument is a single numeric value #' #' @templateVar fn Number #' @template x #' @template na-handling #' @template na.ok #' @template bounds #' @param finite [\code{logical(1)}]\cr #' Check for only finite values? Default is \code{FALSE}. #' @template null.ok #' @template checker #' @useDynLib checkmate c_check_number #' @family scalars #' @export #' @examples #' testNumber(1) #' testNumber(1:2) checkNumber = function(x, na.ok = FALSE, lower = -Inf, upper = Inf, finite = FALSE, null.ok = FALSE) { .Call(c_check_number, x, na.ok, lower, upper, finite, null.ok) } #' @export #' @rdname checkNumber check_number = checkNumber #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkNumber assertNumber = makeAssertionFunction(checkNumber, c.fun = "c_check_number") #' @export #' @rdname checkNumber assert_number = assertNumber #' @export #' @include makeTest.R #' @rdname checkNumber testNumber = makeTestFunction(checkNumber, c.fun = "c_check_number") #' @export #' @rdname checkNumber test_number = testNumber #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkNumber expect_number = makeExpectationFunction(checkNumber, c.fun = "c_check_number") checkmate/R/checkAccess.R0000644000176200001440000000374213115456105014730 0ustar liggesusers#' Check file system access rights #' #' @templateVar fn Access #' @template x #' @param access [\code{character(1)}]\cr #' Single string containing possible characters \sQuote{r}, \sQuote{w} and \sQuote{x} to #' force a check for read, write or execute access rights, respectively. #' Write and executable rights are not checked on Windows. #' @template checker #' @family filesystem #' @export #' @examples #' # Is R's home directory readable? #' testAccess(R.home(), "r") #' #' # Is R's home directory writeable? #' testAccess(R.home(), "w") checkAccess = function(x, access = "") { qassert(access, "S1") if (nzchar(access)) { access = strsplit(access, "")[[1L]] if (anyDuplicated(access) > 0L || !all(access %in% c("r", "w", "x"))) stop("Access pattern invalid, allowed are 'r', 'w' and 'x'") is.win = .Platform$OS.type == "windows" is.root = (!is.win && Sys.info()["user"] == "root") if ("r" %in% access || is.root) { w = wf(file.access(x, 4L) != 0L) if (length(w) > 0L) return(sprintf("'%s' not readable", x[w])) } if (!is.win) { if ("w" %in% access || is.root) { w = wf(file.access(x, 2L) != 0L) if (length(w) > 0L) return(sprintf("'%s' not writeable", x[w])) } if ("x" %in% access) { w = wf(file.access(x, 1L) != 0L) if (length(w) > 0L) return(sprintf("'%s' not executable", x[w])) } } } return(TRUE) } #' @export #' @rdname checkAccess check_access = checkAccess #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkAccess assertAccess = makeAssertionFunction(checkAccess) #' @export #' @rdname checkAccess assert_access = assertAccess #' @export #' @include makeTest.R #' @rdname checkAccess testAccess = makeTestFunction(checkAccess) #' @export #' @rdname checkAccess test_access = testAccess #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkAccess expect_access = makeExpectationFunction(checkAccess) checkmate/R/checkAtomicVector.R0000644000176200001440000000502513015253572016124 0ustar liggesusers#' Check that an argument is an atomic vector #' #' @description #' An atomic vector is defined slightly different from specifications in #' \code{\link[base]{is.atomic}} and \code{\link[base]{is.vector}}: #' An atomic vector is either \code{logical}, \code{integer}, \code{numeric}, #' \code{complex}, \code{character} or \code{raw} and can have any attributes except a #' dimension attribute (like matrices). #' I.e., a \code{factor} is an atomic vector, but a matrix or \code{NULL} are not. #' In short, this is mostly equivalent to \code{is.atomic(x) && !is.null(x) && is.null(dim(x))}. #' #' @templateVar fn AtomicVector #' @template x #' @param any.missing [\code{logical(1)}]\cr #' Are vectors with missing values allowed? Default is \code{TRUE}. #' @param all.missing [\code{logical(1)}]\cr #' Are vectors with only missing values allowed? Default is \code{TRUE}. #' @param len [\code{integer(1)}]\cr #' Exact expected length of \code{x}. #' @param min.len [\code{integer(1)}]\cr #' Minimal length of \code{x}. #' @param max.len [\code{integer(1)}]\cr #' Maximal length of \code{x}. #' @param unique [\code{logical(1)}]\cr #' Must all values be unique? Default is \code{FALSE}. #' @param names [\code{character(1)}]\cr #' Check for names. See \code{\link{checkNamed}} for possible values. #' Default is \dQuote{any} which performs no check at all. #' @template checker #' @family basetypes #' @family atomicvector #' @useDynLib checkmate c_check_atomic_vector #' @export #' @examples #' testAtomicVector(letters, min.len = 1L, any.missing = FALSE) checkAtomicVector = function(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL) { .Call(c_check_atomic_vector, x, any.missing, all.missing, len, min.len, max.len, unique, names) } #' @export #' @rdname checkAtomicVector check_atomic_vector = checkAtomicVector #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkAtomicVector assertAtomicVector = makeAssertionFunction(checkAtomicVector, c.fun = "c_check_atomic_vector") #' @export #' @rdname checkAtomicVector assert_atomic_vector = assertAtomicVector #' @export #' @include makeTest.R #' @rdname checkAtomicVector testAtomicVector = makeTestFunction(checkAtomicVector, c.fun = "c_check_atomic_vector") #' @export #' @rdname checkAtomicVector test_atomic_vector = testAtomicVector #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkAtomicVector expect_atomic_vector = makeExpectationFunction(checkAtomicVector, c.fun = "c_check_atomic_vector") checkmate/R/checkCharacter.R0000644000176200001440000000516513145532305015424 0ustar liggesusers#' Check if an argument is a vector of type character #' #' @templateVar fn Character #' @template x #' @template na-handling #' @inheritParams checkVector #' @param pattern [\code{character(1L)}]\cr #' Regular expression as used in \code{\link[base]{grepl}}. #' All non-missing elements of \code{x} must comply to this pattern. #' @param fixed [\code{character(1)}]\cr #' Substring to detect in \code{x}. Will be used as \code{pattern} in \code{\link[base]{grepl}} #' with option \code{fixed} set to \code{TRUE}. #' All non-missing elements of \code{x} must contain this substring. #' @param ignore.case [\code{logical(1)}]\cr #' See \code{\link[base]{grepl}}. Default is \code{FALSE}. #' @param min.chars [\code{integer(1)}]\cr #' Minimum number of characters for each element of \code{x}. #' @template null.ok #' @template checker #' @family basetypes #' @useDynLib checkmate c_check_character #' @export #' @examples #' testCharacter(letters, min.len = 1, any.missing = FALSE) #' testCharacter(letters, min.chars = 2) #' testCharacter("example", pattern = "xa") checkCharacter = function(x, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) { .Call(c_check_character, x, min.chars, any.missing, all.missing, len, min.len, max.len, unique, names, null.ok) %and% checkCharacterPattern(x, pattern, fixed, ignore.case) } checkCharacterPattern = function(x, pattern = NULL, fixed = NULL, ignore.case = FALSE) { if (!is.null(x)) { if (!is.null(pattern)) { qassert(pattern, "S1") ok = grepl(pattern, x[!is.na(x)], fixed = FALSE, ignore.case = ignore.case) if (!all(ok)) return(sprintf("Must comply to pattern '%s'", pattern)) } if (!is.null(fixed)) { qassert(fixed, "S1") ok = grepl(fixed, x[!is.na(x)], fixed = TRUE, ignore.case = ignore.case) if (!all(ok)) return(sprintf("Must contain substring '%s'", fixed)) } } return(TRUE) } #' @export #' @rdname checkCharacter check_character = checkCharacter #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkCharacter assertCharacter = makeAssertionFunction(checkCharacter) #' @export #' @rdname checkCharacter assert_character = assertCharacter #' @export #' @include makeTest.R #' @rdname checkCharacter testCharacter = makeTestFunction(checkCharacter) #' @export #' @rdname checkCharacter test_character = testCharacter #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkCharacter expect_character = makeExpectationFunction(checkCharacter) checkmate/R/matchArg.R0000644000176200001440000000261313117521546014257 0ustar liggesusers#' Partial Argument Matching #' #' @description #' This is an extensions to \code{\link[base]{match.arg}} with support for \code{\link{AssertCollection}}. #' The behavior is very similar to \code{\link[base]{match.arg}}, except that \code{NULL} is not #' a valid value for \code{x}. #' #' @param x [character]\cr #' User provided argument to match. #' @param choices [character()]\cr #' Candidates to match \code{x} with. #' @param several.ok [logical(1)]\cr #' If \code{TRUE}, multiple matches are allowed, cf. \code{\link[base]{match.arg}}. #' @template add #' @template var.name #' @return Subset of \code{choices}. #' @export #' @examples #' matchArg("k", choices = c("kendall", "pearson")) matchArg = function(x, choices, several.ok = FALSE, .var.name = vname(x), add = NULL) { assertCharacter(choices, min.len = 1L) assertFlag(several.ok) if (several.ok) { if (identical(x, choices)) return(x) assertCharacter(x, min.len = 1L, .var.name = .var.name, add = add) x = choices[pmatch(x, choices, nomatch = 0L, duplicates.ok = TRUE)] assertSubset(x, choices, empty.ok = FALSE, .var.name = .var.name, add = add) } else { if (identical(x, choices)) return(x[1L]) assertCharacter(x, len = 1L, .var.name = .var.name, add = add) x = choices[pmatch(x, choices, nomatch = 0L, duplicates.ok = FALSE)] assertChoice(x, choices, .var.name = .var.name, add = add) } x } checkmate/R/makeExpectation.R0000644000176200001440000000470613115456105015653 0ustar liggesusers#' @title Turn a Check into an Expectation #' #' @description #' \code{makeExpectation} is the internal function used to evaluate the result of a #' check and turn it into an \code{\link[testthat]{expectation}}. #' \code{makeExceptionFunction} can be used to automatically create an expectation #' function based on a check function (see example). #' #' @template x #' @param res [\code{TRUE} | \code{character(1)}]\cr #' The result of a check function: \code{TRUE} for successful checks, #' and an error message as string otherwise. #' @param info [\code{character(1)}]\cr #' See \code{\link[testthat]{expect_that}} #' @param label [\code{character(1)}]\cr #' See \code{\link[testthat]{expect_that}} #' @return \code{makeExpectation} invisibly returns the checked object. #' \code{makeExpectationFunction} returns a \code{function}. #' @export #' @family CustomConstructors #' @include helper.R #' @examples #' # Simple custom check function #' checkFalse = function(x) if (!identical(x, FALSE)) "Must be FALSE" else TRUE #' #' # Create the respective expect function #' expect_false = function(x, info = NULL, label = vname(x)) { #' res = checkFalse(x) #' makeExpectation(x, res, info = info, label = label) #' } #' #' # Alternative: Automatically create such a function #' expect_false = makeExpectationFunction(checkFalse) #' print(expect_false) makeExpectation = function(x, res, info, label) { if (!requireNamespace("testthat", quietly = TRUE)) stop("Package 'testthat' is required for checkmate's 'expect_*' extensions") info = if (is.null(info)) res else sprintf("%s\nAdditional info: %s", res, info) testthat::expect_true(res, info = info, label = sprintf("Check on %s", label)) invisible(x) } #' @rdname makeExpectation #' @template makeFunction #' @export makeExpectationFunction = function(check.fun, c.fun = NULL, env = parent.frame()) { fn.name = if (!is.character(check.fun)) deparse(substitute(check.fun)) else check.fun check.fun = match.fun(check.fun) x = NULL new.fun = function() TRUE formals(new.fun) = c(formals(check.fun), alist(info = NULL, label = vname(x))) tmpl = "{ res = %s(%s); makeExpectation(x, res, info, label) }" if (is.null(c.fun)) { body(new.fun) = parse(text = sprintf(tmpl, fn.name, paste0(names(formals(check.fun)), collapse = ", "))) } else { body(new.fun) = parse(text = sprintf(tmpl, ".Call", paste0(c(c.fun, names(formals(check.fun))), collapse = ", "))) } environment(new.fun) = env return(new.fun) } checkmate/R/coalesce.R0000644000176200001440000000115112762010266014300 0ustar liggesusers#' @title Coalesce operator #' @rdname coalesce #' #' @description #' Returns the left hand side if not missing nor \code{NULL}, and #' the right hand side otherwise. #' #' @param lhs [any]\cr #' Left hand side of the operator. Is returned if not missing or \code{NULL}. #' @param rhs [any]\cr #' Right hand side of the operator. Is returned if \code{lhs} is missing or \code{NULL}. #' @return Either \code{lhs} or \code{rhs}. #' @export #' @examples #' print(NULL %??% 1 %??% 2) #' print(names(iris) %??% letters[seq_len(ncol(iris))]) "%??%" = function(lhs, rhs) { if (missing(lhs) || is.null(lhs)) rhs else lhs } checkmate/R/checkInt.R0000644000176200001440000000213113063727166014262 0ustar liggesusers#' Check if an argument is a single integerish value #' #' @templateVar fn Int #' @template x #' @template na-handling #' @template na.ok #' @template bounds #' @template tol #' @template null.ok #' @template checker #' @template note-convert #' @family scalars #' @useDynLib checkmate c_check_int #' @export #' @examples #' testInt(1) #' testInt(-1, lower = 0) checkInt = function(x, na.ok = FALSE, lower = -Inf, upper = Inf, tol = sqrt(.Machine$double.eps), null.ok = FALSE) { .Call(c_check_int, x, na.ok, lower, upper, tol, null.ok) } #' @export #' @rdname checkInt check_int = checkInt #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkInt assertInt = makeAssertionFunction(checkInt, c.fun = "c_check_int") #' @export #' @rdname checkInt assert_int = assertInt #' @export #' @include makeTest.R #' @rdname checkInt testInt = makeTestFunction(checkInt, c.fun = "c_check_int") #' @export #' @rdname checkInt test_int = testInt #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkInt expect_int = makeExpectationFunction(checkInt, c.fun = "c_check_int") checkmate/R/checkIntegerish.R0000644000176200001440000000346013155456045015634 0ustar liggesusers#' @title Check if an object is an integerish vector #' #' @description #' An integerish value is defined as value safely convertible to integer. #' This includes integers and numeric values which are close to an integer #' w.r.t. a numeric tolerance. #' #' @note #' To convert from integerish to integer, use \code{\link{asInteger}}. #' #' @templateVar fn Integerish #' @template x #' @template na-handling #' @inheritParams checkInteger #' @inheritParams checkVector #' @template sorted #' @template tol #' @template null.ok #' @template checker #' @family basetypes #' @useDynLib checkmate c_check_integerish #' @export #' @examples #' testIntegerish(1L) #' testIntegerish(1.) #' testIntegerish(1:2, lower = 1L, upper = 2L, any.missing = FALSE) checkIntegerish = function(x, tol = sqrt(.Machine$double.eps), lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) { .Call(c_check_integerish, x, tol, lower, upper, any.missing, all.missing, len, min.len, max.len, unique, sorted, names, null.ok) } #' @export #' @rdname checkIntegerish check_integerish = checkIntegerish #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkIntegerish assertIntegerish = makeAssertionFunction(checkIntegerish, c.fun = "c_check_integerish") #' @export #' @rdname checkIntegerish assert_integerish = assertIntegerish #' @export #' @include makeTest.R #' @rdname checkIntegerish testIntegerish = makeTestFunction(checkIntegerish, c.fun = "c_check_integerish") #' @export #' @rdname checkIntegerish test_integerish = testIntegerish #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkIntegerish expect_integerish = makeExpectationFunction(checkIntegerish, c.fun = "c_check_integerish") checkmate/R/checkDataTable.R0000644000176200001440000000513113162404132015335 0ustar liggesusers#' Check if an argument is a data table #' #' @templateVar fn DataTable #' @template x #' @inheritParams checkMatrix #' @inheritParams checkList #' @inheritParams checkDataFrame #' @param key [\code{character}]\cr #' Expected primary key(s) of the data table. #' @param index [\code{character}]\cr #' Expected secondary key(s) of the data table. #' @template null.ok #' @template checker #' @family compound #' @export #' @examples #' library(data.table) #' dt = as.data.table(iris) #' setkeyv(dt, "Species") #' setkeyv(dt, "Sepal.Length", physical = FALSE) #' testDataTable(dt) #' testDataTable(dt, key = "Species", index = "Sepal.Length", any.missing = FALSE) checkDataTable = function(x, key = NULL, index = NULL, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) { if (!requireNamespace("data.table", quietly = TRUE)) stop("Install package 'data.table' to perform checks of data tables") qassert(null.ok, "B1") if (is.null(x)) { if (null.ok) return(TRUE) return("Must be a data.table, not 'NULL'") } if (!data.table::is.data.table(x)) { return(paste0("Must be a data.table", if (null.ok) " (or 'NULL')" else "", sprintf(", not %s", guessType(x)))) } checkDataFrame(x, types, any.missing, all.missing, min.rows, min.cols, nrows, ncols, row.names, col.names, null.ok = FALSE) %and% checkDataTableProps(x, key, index) } checkDataTableProps = function(x, key = NULL, index = NULL) { if (!is.null(key)) { qassert(key, "S") if (!setequal(data.table::key(x) %??% character(0L), key)) return(sprintf("Must have primary keys: %s", paste0(key, collapse = ","))) } if (!is.null(index)) { qassert(index, "S") indices = strsplit(data.table::indices(x) %??% "", "__", fixed = TRUE)[[1L]] if (!setequal(indices, index)) return(sprintf("Must have secondary keys (indices): %s", paste0(index, collapse = ","))) } return(TRUE) } #' @export #' @rdname checkDataTable check_data_table = checkDataTable #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkDataTable assertDataTable = makeAssertionFunction(checkDataTable) #' @export #' @rdname checkDataTable assert_data_table = assertDataTable #' @export #' @include makeTest.R #' @rdname checkDataTable testDataTable = makeTestFunction(checkDataTable) #' @export #' @rdname checkDataTable test_data_table = testDataTable #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkDataTable expect_data_table = makeExpectationFunction(checkDataTable) checkmate/R/checkSetEqual.R0000644000176200001440000000356713167073256015270 0ustar liggesusers#' Check if an argument is equal to a given set #' #' @templateVar fn Subset #' @template x #' @param y [\code{atomic}]\cr #' Set to compare with. #' @param ordered [\code{logical(1)}]\cr #' Check \code{x} to have the same length and order as \code{y}, i.e. #' check using \dQuote{==} while handling \code{NA}s nicely. #' Default is \code{FALSE}. #' @template fmatch #' @template checker #' @template set #' @family set #' @export #' @examples #' testSetEqual(c("a", "b"), c("a", "b")) #' testSetEqual(1:3, 1:4) #' #' # x is not converted before the comparison (except for numerics) #' testSetEqual(factor("a"), "a") #' testSetEqual(1, "1") #' testSetEqual(1, as.integer(1)) checkSetEqual = function(x, y, ordered = FALSE, fmatch = FALSE) { qassert(x, "a") qassert(y, "a") qassert(ordered, "B1") if (ordered) { if (!isSameType(x, y) || length(x) != length(y) || any(xor(is.na(x), is.na(y)) | x != y, na.rm = TRUE)) return(sprintf("Must be equal to {'%s'}", paste0(y, collapse = "','"))) } else { if (isTRUE(fmatch) && requireNamespace("fastmatch", quietly = TRUE)) match = fastmatch::fmatch if (!isSameType(x, y) || any(match(x, y, 0L) == 0L) || any(match(y, x, 0L) == 0L)) return(sprintf("Must be equal to set {'%s'}", paste0(y, collapse = "','"))) } return(TRUE) } #' @export #' @rdname checkSetEqual check_set_equal = checkSetEqual #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkSetEqual assertSetEqual = makeAssertionFunction(checkSetEqual) #' @export #' @rdname checkSetEqual assert_set_equal = assertSetEqual #' @export #' @include makeTest.R #' @rdname checkSetEqual testSetEqual = makeTestFunction(checkSetEqual) #' @export #' @rdname checkSetEqual test_set_equal = testSetEqual #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkSetEqual expect_set_equal = makeExpectationFunction(checkSetEqual) checkmate/R/makeTest.R0000644000176200001440000000354012762010266014303 0ustar liggesusers#' @title Turn a Check into a Test #' #' @description #' \code{makeTest} is the internal function used to evaluate the result of a #' check and throw an exception if necessary. #' This function is currently only a stub and just calls \code{\link[base]{isTRUE}}. #' \code{makeTestFunction} can be used to automatically create an assertion #' function based on a check function (see example). #' #' @param res [\code{TRUE} | \code{character(1)}]\cr #' The result of a check function: \code{TRUE} for successful checks, #' and an error message as string otherwise. #' @return \code{makeTest} returns \code{TRUE} if the check is successful and \code{FALSE} otherwise. #' \code{makeTestFunction} returns a \code{function}. #' @export #' @family CustomConstructors #' @include helper.R #' @examples #' # Simple custom check function #' checkFalse = function(x) if (!identical(x, FALSE)) "Must be FALSE" else TRUE #' #' # Create the respective test function #' testFalse = function(x) { #' res = checkFalse(x) #' makeTest(res) #' } #' #' # Alternative: Automatically create such a function #' testFalse = makeTestFunction(checkFalse) #' print(testFalse) makeTest = function(res) { identical(res, TRUE) } #' @rdname makeTest #' @template makeFunction #' @export makeTestFunction = function(check.fun, c.fun = NULL, env = parent.frame()) { fn.name = if (!is.character(check.fun)) deparse(substitute(check.fun)) else check.fun check.fun = match.fun(check.fun) new.fun = function() TRUE formals(new.fun) = formals(check.fun) tmpl = "{ identical(%s(%s), TRUE) }" if (is.null(c.fun)) { body(new.fun) = parse(text = sprintf(tmpl, fn.name, paste0(names(formals(check.fun)), collapse = ", "))) } else { body(new.fun) = parse(text = sprintf(tmpl, ".Call", paste0(c(c.fun, names(formals(check.fun))), collapse = ", "))) } environment(new.fun) = env return(new.fun) } checkmate/R/checkLogical.R0000644000176200001440000000241113160423672015074 0ustar liggesusers#' Check if an argument is a vector of type logical #' #' @templateVar fn Logical #' @template x #' @template na-handling #' @inheritParams checkVector #' @template null.ok #' @template checker #' @family basetypes #' @seealso \code{\link{checkBit}} #' @useDynLib checkmate c_check_logical #' @export #' @examples #' testLogical(TRUE) #' testLogical(TRUE, min.len = 1) checkLogical = function(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) { .Call(c_check_logical, x, any.missing, all.missing, len, min.len, max.len, unique, names, null.ok) } #' @export #' @rdname checkLogical check_logical = checkLogical #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkLogical assertLogical = makeAssertionFunction(checkLogical, c.fun = "c_check_logical") #' @export #' @rdname checkLogical assert_logical = assertLogical #' @export #' @include makeTest.R #' @rdname checkLogical testLogical = makeTestFunction(checkLogical, c.fun = "c_check_logical") #' @export #' @rdname checkLogical test_logical = testLogical #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkLogical expect_logical = makeExpectationFunction(checkLogical, c.fun = "c_check_logical") checkmate/R/asInteger.R0000644000176200001440000000345513064452167014462 0ustar liggesusers#' Convert an argument to an integer #' #' @description #' \code{asInteger} is intended to be used for vectors while \code{asInt} is #' a specialization for scalar integers and \code{asCount} for scalar #' non-negative integers. #' Convertible are (a) atomic vectors with all elements \code{NA} #' and (b) double vectors with all elements being within \code{tol} #' range of an integer. #' #' @param x [any]\cr #' Object to convert. #' @template na-handling #' @inheritParams checkInteger #' @inheritParams checkVector #' @template tol #' @template var.name #' @return Converted \code{x}. #' @export #' @examples #' asInteger(c(1, 2, 3)) #' asCount(1) #' asInt(1) asInteger = function(x, tol = sqrt(.Machine$double.eps), lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, .var.name = vname(x)) { assertIntegerish(x, tol = tol, lower = lower, upper = upper, any.missing = any.missing, all.missing = all.missing, len = len, min.len = min.len, max.len = max.len, unique = unique, sorted = sorted, names = names, null.ok = FALSE, .var.name = .var.name) storage.mode(x) = "integer" x } #' @rdname asInteger #' @param positive [\code{logical(1)}]\cr #' Must \code{x} be positive (>= 1)? #' Default is \code{FALSE}. #' @template na.ok #' @export asCount = function(x, na.ok = FALSE, positive = FALSE, tol = sqrt(.Machine$double.eps), .var.name = vname(x)) { assertCount(x, na.ok, positive, tol, .var.name = .var.name) storage.mode(x) = "integer" x } #' @rdname asInteger #' @template bounds #' @export asInt = function(x, na.ok = FALSE, lower = -Inf, upper = Inf, tol = sqrt(.Machine$double.eps), .var.name = vname(x)) { assertInt(x, na.ok, lower, upper, tol, .var.name = .var.name) storage.mode(x) = "integer" x } checkmate/R/makeAssertion.R0000644000176200001440000000530513154245350015334 0ustar liggesusers#' @title Turn a Check into an Assertion #' #' @description #' \code{makeAssertion} is the internal function used to evaluate the result of a #' check and throw an exception if necessary. #' \code{makeAssertionFunction} can be used to automatically create an assertion #' function based on a check function (see example). #' #' @template x #' @param res [\code{TRUE} | \code{character(1)}]\cr #' The result of a check function: \code{TRUE} for successful checks, #' and an error message as string otherwise. #' @param var.name [\code{character(1)}]\cr #' The custom name for \code{x} as passed to any \code{assert*} function. #' Defaults to a heuristic name lookup. #' @param collection [\code{\link{AssertCollection}}]\cr #' If an \code{\link{AssertCollection}} is provided, the error message is stored #' in it. If \code{NULL}, an exception is raised if \code{res} is not #' \code{TRUE}. #' @return \code{makeAssertion} invisibly returns the checked object if the check was successful, #' and an exception is raised (or its message stored in the collection) otherwise. #' \code{makeAssertionFunction} returns a \code{function}. #' @export #' @family CustomConstructors #' @include helper.R #' @examples #' # Simple custom check function #' checkFalse = function(x) if (!identical(x, FALSE)) "Must be FALSE" else TRUE #' #' # Create the respective assert function #' assertFalse = function(x, .var.name = vname(x), add = NULL) { #' res = checkFalse(x) #' makeAssertion(x, res, .var.name, add) #' } #' #' # Alternative: Automatically create such a function #' assertFalse = makeAssertionFunction(checkFalse) #' print(assertFalse) makeAssertion = function(x, res, var.name, collection) { if (!identical(res, TRUE)) { if (is.null(collection)) mstop("Assertion on '%s' failed: %s.", var.name, res) assertClass(collection, "AssertCollection", .var.name = "add") collection$push(sprintf("Variable '%s': %s.", var.name, res)) } return(invisible(x)) } #' @rdname makeAssertion #' @template makeFunction #' @export makeAssertionFunction = function(check.fun, c.fun = NULL, env = parent.frame()) { fn.name = if (!is.character(check.fun)) deparse(substitute(check.fun)) else check.fun check.fun = match.fun(check.fun) x = NULL new.fun = function() TRUE formals(new.fun) = c(formals(check.fun), alist(.var.name = vname(x), add = NULL)) tmpl = "{ res = %s(%s); makeAssertion(x, res, .var.name, add) }" if (is.null(c.fun)) { body(new.fun) = parse(text = sprintf(tmpl, fn.name, paste0(names(formals(check.fun)), collapse = ", "))) } else { body(new.fun) = parse(text = sprintf(tmpl, ".Call", paste0(c(c.fun, names(formals(check.fun))), collapse = ", "))) } environment(new.fun) = env return(new.fun) } checkmate/R/checkComplex.R0000644000176200001440000000232612762010266015134 0ustar liggesusers#' Check if an argument is a vector of type complex #' #' @templateVar fn Complex #' @template x #' @template na-handling #' @inheritParams checkVector #' @template null.ok #' @template checker #' @family basetypes #' @useDynLib checkmate c_check_complex #' @export #' @examples #' testComplex(1) #' testComplex(1+1i) checkComplex = function(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) { .Call(c_check_complex, x, any.missing, all.missing, len, min.len, max.len, unique, names, null.ok) } #' @export #' @rdname checkComplex check_complex = checkComplex #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkComplex assertComplex = makeAssertionFunction(checkComplex, c.fun = "c_check_complex") #' @export #' @rdname checkComplex assert_complex = assertComplex #' @export #' @include makeTest.R #' @rdname checkComplex testComplex = makeTestFunction(checkComplex, c.fun = "c_check_complex") #' @export #' @rdname checkComplex test_complex = testComplex #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkComplex expect_complex = makeExpectationFunction(checkComplex, c.fun = "c_check_complex") checkmate/R/assert.R0000644000176200001440000000440513154244635014035 0ustar liggesusers#' Combine multiple checks into one assertion #' #' @description #' You can call this function with an arbitrary number of of \code{check*} #' functions, i.e. functions provided by this package or your own functions which #' return \code{TRUE} on success and the error message as \code{character(1)} otherwise. #' The resulting assertion is successful, if \code{combine} is #' \dQuote{or} (default) and at least one check evaluates to \code{TRUE} or #' \code{combine} is \dQuote{and} and all checks evaluate to \code{TRUE}. #' Otherwise, \code{assert} throws an informative error message. #' #' @param ... [any]\cr #' List of calls to check functions. #' @param combine [\code{character(1)}]\cr #' \dQuote{or} or \dQuote{and} to combine the check functions with an OR #' or AND, respectively. #' @template var.name #' @return Throws an error if all checks fail and invisibly returns #' \code{TRUE} otherwise. #' @export #' @examples #' x = 1:10 #' assert(checkNull(x), checkInteger(x, any.missing = FALSE)) #' \dontrun{ #' x = 1 #' assert(checkChoice(x, c("a", "b")), checkDataFrame(x)) #' } assert = function(..., combine = "or", .var.name = NULL) { assertChoice(combine, c("or", "and")) dots = match.call(expand.dots = FALSE)$... env = parent.frame() if (combine == "or") { msgs = character(length(dots)) for (i in seq_along(dots)) { val = eval(dots[[i]], envir = env) if (identical(val, TRUE)) return(invisible(TRUE)) msgs[i] = as.character(val) } if (is.null(.var.name)) .var.name = vapply(dots, function(x) as.character(x)[2L], FUN.VALUE = NA_character_) if (length(msgs) > 1L) { msgs = sprintf("%s(%s): %s", vapply(dots, function(x) as.character(x)[1L], FUN.VALUE = NA_character_), .var.name, msgs) msgs = paste0(c("One of the following must apply:", strwrap(msgs, prefix = " * ")), collapse = "\n") mstop("Assertion failed. %s", msgs) } else { mstop("Assertion on '%s' failed. %s.", .var.name, msgs) } } else { for (i in seq_along(dots)) { val = eval(dots[[i]], envir = env) if (!identical(val, TRUE)) { if (is.null(.var.name)) .var.name = as.character(dots[[1L]])[2L] mstop("Assertion on '%s' failed. %s.", .var.name, val) } } } invisible(TRUE) } checkmate/R/vname.R0000644000176200001440000000072513032414503013627 0ustar liggesusers#' @title Lookup a variable name #' @description #' Tries to heuristically determine the variable name of \code{x} in the parent frame #' with a combination of \code{\link[base]{deparse}} and \code{\link[base]{substitute}}. #' Used for checkmate's error messages. #' @param x [ANY]\cr #' Object. #' @return [\code{character(1)}] Variable name. #' @export vname = function(x) { paste0(deparse(substitute(x, parent.frame(1L)), width.cutoff = 500), collapse = "\n") } checkmate/R/checkFileExists.R0000644000176200001440000000502112762010266015577 0ustar liggesusers#' Check existence and access rights of files #' #' @note #' The functions without the suffix \dQuote{exists} are deprecated and will be removed #' from the package in a future version due to name clashes. #' \code{test_file} has been unexported already. #' #' @templateVar fn FileExists #' @template x #' @inheritParams checkAccess #' @param extension [\code{character}]\cr #' Vector of allowed file extensions, matched case insensitive. #' @template checker #' @family filesystem #' @export #' @examples #' # Check if R's COPYING file is readable #' testFileExists(file.path(R.home(), "COPYING"), access = "r") #' #' # Check if R's COPYING file is readable and writable #' testFileExists(file.path(R.home(), "COPYING"), access = "rw") checkFileExists = function(x, access = "", extension = NULL) { if (!qtest(x, "S+")) return("No file provided") w = wf(dir.exists(x)) if (length(w) > 0L) return(sprintf("File expected, but directory in place: '%s'", x[w])) w = wf(!file.exists(x)) if (length(w) > 0L) return(sprintf("File does not exist: '%s'", x[w])) checkAccess(x, access) %and% checkFileExtension(x, extension) } checkFileExtension = function(x, extension = NULL) { if (!is.null(extension)) { qassert(extension, "S+") pos = regexpr("\\.([[:alnum:]]+)$", x) ext = ifelse(pos > -1L, tolower(substring(x, pos + 1L)), "") if (any(ext %nin% tolower(extension))) return(sprintf("File extension must be in {'%s'}", paste0(extension, collapse = "','"))) } return(TRUE) } #' @export #' @rdname checkFileExists check_file_exists = checkFileExists #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkFileExists assertFileExists = makeAssertionFunction(checkFileExists) #' @export #' @rdname checkFileExists assert_file_exists = assertFileExists #' @export #' @include makeTest.R #' @rdname checkFileExists testFileExists = makeTestFunction(checkFileExists) #' @export #' @rdname checkFileExists test_file_exists = testFileExists #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkFileExists expect_file_exists = makeExpectationFunction(checkFileExists) #' @export #' @rdname checkFileExists checkFile = checkFileExists #' @export #' @rdname checkFileExists assertFile = assertFileExists #' @export #' @rdname checkFileExists assert_file = assert_file_exists #' @export #' @rdname checkFileExists testFile = testFileExists ##' @export ##' @rdname checkFileExists ## test_file = test_file_exists #' @export #' @rdname checkFileExists expect_file = expect_file_exists checkmate/R/isIntegerish.R0000644000176200001440000000021112762037177015165 0ustar liggesusers#' @useDynLib checkmate c_is_integerish isIntegerish = function(x, tol = sqrt(.Machine$double.eps)) { .Call(c_is_integerish, x, tol) } checkmate/R/checkCount.R0000644000176200001440000000242513155456103014616 0ustar liggesusers#' Check if an argument is a count #' #' @description #' A count is defined as non-negative integerish value. #' #' @templateVar fn Count #' @template x #' @template na-handling #' @template na.ok #' @param positive [\code{logical(1)}]\cr #' Must \code{x} be positive (>= 1)? #' Default is \code{FALSE}, allowing 0. #' @template tol #' @template null.ok #' @template checker #' @template note-convert #' @family scalars #' @useDynLib checkmate c_check_count #' @export #' @examples #' testCount(1) #' testCount(-1) checkCount = function(x, na.ok = FALSE, positive = FALSE, tol = sqrt(.Machine$double.eps), null.ok = FALSE) { .Call(c_check_count, x, na.ok, positive, tol, null.ok) } #' @export #' @rdname checkCount check_count = checkCount #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkCount assertCount = makeAssertionFunction(checkCount, c.fun = "c_check_count") #' @export #' @rdname checkCount assert_count = assertCount #' @export #' @include makeTest.R #' @rdname checkCount testCount = makeTestFunction(checkCount, c.fun = "c_check_count") #' @export #' @rdname checkCount test_count = testCount #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkCount expect_count = makeExpectationFunction(checkCount, c.fun = "c_check_count") checkmate/R/checkAtomic.R0000644000176200001440000000237213167637071014753 0ustar liggesusers#' Check that an argument is an atomic vector #' #' @description #' For the definition of \dQuote{atomic}, see \code{\link[base]{is.atomic}}. #' #' @templateVar fn Atomic #' @template x #' @inheritParams checkVector #' @template checker #' @useDynLib checkmate c_check_atomic #' @export #' @family basetypes #' @family atomicvector #' @examples #' testAtomic(letters, min.len = 1L, any.missing = FALSE) checkAtomic = function(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL) { .Call(c_check_atomic, x, any.missing, all.missing, len, min.len, max.len, unique, names) } #' @export #' @rdname checkAtomic check_atomic = checkAtomic #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkAtomic assertAtomic = makeAssertionFunction(checkAtomic, c.fun = "c_check_atomic") #' @export #' @rdname checkAtomic assert_atomic = assertAtomic #' @export #' @include makeTest.R #' @rdname checkAtomic testAtomic = makeTestFunction(checkAtomic, c.fun = "c_check_atomic") #' @export #' @rdname checkAtomic test_atomic = testAtomic #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkAtomic expect_atomic = makeExpectationFunction(checkAtomic, c.fun = "c_check_atomic") checkmate/R/checkScalar.R0000644000176200001440000000201712762010266014727 0ustar liggesusers#' Check if an argument is a single atomic value #' #' @templateVar fn Scalar #' @template x #' @template na-handling #' @template na.ok #' @template null.ok #' @template checker #' @family scalars #' @useDynLib checkmate c_check_scalar #' @export #' @examples #' testScalar(1) #' testScalar(1:10) checkScalar = function(x, na.ok = FALSE, null.ok = FALSE) { .Call(c_check_scalar, x, na.ok, null.ok) } #' @export #' @rdname checkScalar check_scalar = checkScalar #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkScalar assertScalar = makeAssertionFunction(checkScalar, c.fun = "c_check_scalar") #' @export #' @rdname checkScalar assert_scalar = assertScalar #' @export #' @include makeTest.R #' @rdname checkScalar testScalar = makeTestFunction(checkScalar, c.fun = "c_check_scalar") #' @export #' @rdname checkScalar test_scalar = testScalar #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkScalar expect_scalar = makeExpectationFunction(checkScalar, c.fun = "c_check_scalar") checkmate/R/wfwl.R0000644000176200001440000000157213004124520013475 0ustar liggesusers#' @title Get the index of the first/last TRUE #' #' @description #' A quick C implementation for \dQuote{which.first} (\code{head(which(x), 1)}) and #' \dQuote{which.last} (\code{tail(which(x), 1)}). #' #' @param x [\code{logical}]\cr #' Logical vector. #' @param use.names [\code{logical(1)}]\cr #' If \code{TRUE} and \code{x} is named, the result is also #' named. #' @return [\code{integer(1)} | \code{integer(0)}]. #' Returns the index of the first/last \code{TRUE} value in \code{x} or #' an empty integer vector if none is found. NAs are ignored. #' @useDynLib checkmate c_which_first #' @export #' @examples #' wf(c(FALSE, TRUE)) #' wl(c(FALSE, FALSE)) #' wf(NA) wf = function(x, use.names = TRUE) { .Call(c_which_first, x, use.names) } #' @rdname wf #' @export #' @useDynLib checkmate c_which_last wl = function(x, use.names = TRUE) { .Call(c_which_last, x, use.names) } checkmate/R/checkList.R0000644000176200001440000000526013154202356014437 0ustar liggesusers#' Check if an argument is a list #' #' @note #' The test for uniqueness does differentiate between the different NA types in R. #' This is require to be consistent with \code{\link[base]{unique}} while checking #' scalar missing values. Also see the example. #' #' @templateVar fn List #' @template x #' @inheritParams checkVector #' @param ... [any]\cr #' Additional parameters used in a call of \code{\link{checkVector}}. #' @param types [\code{character}]\cr #' Character vector of class names. Each list element must inherit #' from at least one of the provided types. #' The types \dQuote{logical}, \dQuote{integer}, \dQuote{integerish}, \dQuote{double}, #' \dQuote{numeric}, \dQuote{complex}, \dQuote{character}, \dQuote{factor}, \dQuote{atomic}, \dQuote{vector} #' \dQuote{atomicvector}, \dQuote{array}, \dQuote{matrix}, \dQuote{list}, \dQuote{function}, #' \dQuote{environment} and \dQuote{null} are supported. #' For other types \code{\link[base]{inherits}} is used as a fallback to check \code{x}'s inheritance. #' Defaults to \code{character(0)} (no check). #' @template null.ok #' @template checker #' @family basetypes #' @export #' @useDynLib checkmate c_check_list #' @examples #' testList(list()) #' testList(as.list(iris), types = c("numeric", "factor")) #' #' # Uniqueness differentiates between different NA types: #' testList(list(NA, NA), unique = TRUE) #' testList(list(NA, NA_real_), unique = TRUE) checkList = function(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) { .Call(c_check_list, x, any.missing, all.missing, len, min.len, max.len, unique, names, null.ok) %and% checkListTypes(x, types) } checkListTypes = function(x, types = character(0L)) { if (is.null(x) || length(types) == 0L) return(TRUE) qassert(types, "S") ind = seq_along(x) for (type in types) { f = checkmate$listtypefuns[[type]] %??% function(x) inherits(x, type) ind = ind[!vapply(x[ind], f, FUN.VALUE = NA, USE.NAMES = FALSE)] if (length(ind) == 0L) return(TRUE) } return(sprintf("May only contain the following types: %s", paste0(types, collapse = ","))) } #' @export #' @rdname checkList check_list = checkList #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkList assertList = makeAssertionFunction(checkList) #' @export #' @rdname checkList assert_list = assertList #' @export #' @include makeTest.R #' @rdname checkList testList = makeTestFunction(checkList) #' @export #' @rdname checkList test_list = testList #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkList expect_list = makeExpectationFunction(checkList) checkmate/R/checkSubset.R0000644000176200001440000000366413170102716014774 0ustar liggesusers#' Check if an argument is a subset of a given set #' #' @templateVar fn Subset #' @template x #' @param choices [\code{atomic}]\cr #' Set of possible values. May be empty. #' @param empty.ok [\code{logical(1)}]\cr #' Treat zero-length \code{x} as subset of any set \code{choices} (this includes \code{NULL})? #' Default is \code{TRUE}. #' @template fmatch #' @template checker #' @template set #' @family set #' @export #' @examples #' testSubset(c("a", "z"), letters) #' testSubset("ab", letters) #' testSubset("Species", names(iris)) #' #' # x is not converted before the comparison (except for numerics) #' testSubset(factor("a"), "a") #' testSubset(1, "1") #' testSubset(1, as.integer(1)) checkSubset = function(x, choices, empty.ok = TRUE, fmatch = FALSE) { qassert(empty.ok, "B1") if (length(x) == 0L) { if (!empty.ok) return(sprintf("Must be a subset of {'%s'}, not empty", paste0(choices, collapse = "','"))) return(TRUE) } qassert(choices, "a") if (length(choices) == 0L) { if (length(x) == 0L) return(TRUE) return("Must be a subset of the empty set, i.e. also empty") } if (isTRUE(fmatch) && requireNamespace("fastmatch", quietly = TRUE)) match = fastmatch::fmatch if (!is.null(x) && (!isSameType(x, choices) || any(match(x, choices, 0L) == 0L))) return(sprintf("Must be a subset of {'%s'}", paste0(choices, collapse = "','"))) return(TRUE) } #' @export #' @rdname checkSubset check_subset = checkSubset #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkSubset assertSubset = makeAssertionFunction(checkSubset) #' @export #' @rdname checkSubset assert_subset = assertSubset #' @export #' @include makeTest.R #' @rdname checkSubset testSubset = makeTestFunction(checkSubset) #' @export #' @rdname checkSubset test_subset = testSubset #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkSubset expect_subset = makeExpectationFunction(checkSubset) checkmate/R/qassert.R0000644000176200001440000001174613115456105014216 0ustar liggesusers#' @title Quick argument checks on (builtin) R types #' #' @description #' The provided functions parse rules which allow to express some of the most #' frequent argument checks by typing just a few letters. #' #' @param x [any]\cr #' Object the check. #' @param rules [\code{character}]\cr #' Set of rules. See details. #' @template var.name #' @return #' \code{qassert} throws an \code{R} exception if object \code{x} does #' not comply to at least one of the \code{rules} and returns the tested object invisibly #' otherwise. #' \code{qtest} behaves the same way but returns \code{FALSE} if none of the #' \code{rules} comply. #' \code{qexpect} is intended to be inside the unit test framework \code{\link[testthat]{testthat}} and #' returns an \code{\link[testthat]{expectation}}. #' #' @details #' The rule is specified in up to three parts. #' \enumerate{ #' \item{ #' Class and missingness check. #' The first letter is an abbreviation for the class. If it is #' provided uppercase, missing values are prohibited. #' Supported abbreviations: #' \tabular{rl}{ #' \code{[bB]} \tab Bool / logical.\cr #' \code{[iI]} \tab Integer.\cr #' \code{[xX]} \tab Integerish (numeric convertible to integer, see \code{\link{checkIntegerish}}).\cr #' \code{[rR]} \tab Real / double.\cr #' \code{[cC]} \tab Complex.\cr #' \code{[nN]} \tab Numeric (integer or double).\cr #' \code{[sS]} \tab String / character.\cr #' \code{[fF]} \tab Factor\cr #' \code{[aA]} \tab Atomic.\cr #' \code{[vV]} \tab Atomic vector (see \code{\link{checkAtomicVector}}).\cr #' \code{[lL]} \tab List. Missingness is defined as \code{NULL} element.\cr #' \code{[mM]} \tab Matrix.\cr #' \code{[dD]} \tab Data.frame. Missingness is checked recursively on columns.\cr #' \code{[e]} \tab Environment.\cr #' \code{[0]} \tab \code{NULL}.\cr #' \code{[*]} \tab placeholder to allow any type. #' } #' Note that the check for missingness does not distinguish between #' \code{NaN} and \code{NA}. Infinite values are not treated as missing, but #' can be caught using boundary checks (part 3). #' } #' \item{ #' Length definition. This can be one of #' \tabular{rl}{ #' \code{[*]} \tab any length,\cr #' \code{[?]} \tab length of zero or one,\cr #' \code{[+]} \tab length of at least one, or\cr #' \code{[0-9]+} \tab exact length specified as integer. #' } #' Preceding the exact length with one of the comparison operators \code{=}/\code{==}, #' \code{<}, \code{<=}, \code{>=} or \code{>} is also supported. #' } #' \item{ #' Range check as two numbers separated by a comma, enclosed by square brackets #' (endpoint included) or parentheses (endpoint excluded). #' For example, \dQuote{[0, 3)} results in \code{all(x >= 0 & x < 3)}. #' The lower and upper bound may be omitted which is the equivalent of a negative or #' positive infinite bound, respectively. #' By definition \code{[0,]} contains \code{Inf}, while \code{[0,)} does not. #' The same holds for the left (lower) boundary and \code{-Inf}. #' E.g., the rule \dQuote{N1()} checks for a single finite numeric which is not NA, #' while \dQuote{N1[)} allows \code{-Inf}. #' } #' } #' @note #' The functions are inspired by the blog post of Bogumił Kamiński: #' \url{http://rsnippets.blogspot.de/2013/06/testing-function-agruments-in-gnu-r.html}. #' The implementation is mostly written in C to minimize the overhead. #' @seealso \code{\link{qtestr}} and \code{\link{qassertr}} for efficient checks #' of list elements and data frame columns. #' @useDynLib checkmate c_qassert #' @export #' @examples #' # logical of length 1 #' qtest(NA, "b1") #' #' # logical of length 1, NA not allowed #' qtest(NA, "B1") #' #' # logical of length 0 or 1, NA not allowed #' qtest(TRUE, "B?") #' #' # numeric with length > 0 #' qtest(runif(10), "n+") #' #' # integer with length > 0, NAs not allowed, all integers >= 0 and < Inf #' qtest(1:3, "I+[0,)") #' #' # either an emtpy list or a character vector with <=5 elements #' qtest(1, c("l0", "s<=5")) #' #' # data frame with at least one column and no missing value in any column #' qtest(iris, "D+") qassert = function(x, rules, .var.name = vname(x)) { res = .Call(c_qassert, x, rules, FALSE) if (!identical(res, TRUE)) mstop(qmsg(res, .var.name)) invisible(x) } #' @useDynLib checkmate c_qtest #' @rdname qassert #' @export qtest = function(x, rules) { .Call(c_qtest, x, rules, FALSE, 1L) } #' @useDynLib checkmate c_qassert #' @template expect #' @rdname qassert #' @include makeExpectation.R #' @export qexpect = function(x, rules, info = NULL, label = vname(x)) { res = .Call(c_qassert, x, rules, FALSE) if (!identical(res, TRUE)) res = qmsg(res, label) makeExpectation(x, res, info = info, label = label) } qmsg = function(msg, vname) { if (length(msg) > 1L) msg = paste0(c("One of the following must apply:", strwrap(msg, prefix = " * ")), collapse = "\n") sprintf("Assertion on '%s' failed. %s.", vname, msg) } checkmate/R/checkDataFrame.R0000644000176200001440000000255412762010266015354 0ustar liggesusers#' Check if an argument is a data frame #' #' @templateVar fn DataFrame #' @template x #' @inheritParams checkMatrix #' @inheritParams checkList #' @template null.ok #' @template checker #' @family compound #' @family basetypes #' @export #' @useDynLib checkmate c_check_dataframe #' @examples #' testDataFrame(iris) #' testDataFrame(iris, types = c("numeric", "factor"), min.rows = 1, col.names = "named") checkDataFrame = function(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) { .Call(c_check_dataframe, x, any.missing, all.missing, min.rows, min.cols, nrows, ncols, row.names, col.names, null.ok) %and% checkListTypes(x, types) } #' @export #' @rdname checkDataFrame check_data_frame = checkDataFrame #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkDataFrame assertDataFrame = makeAssertionFunction(checkDataFrame) #' @export #' @rdname checkDataFrame assert_data_frame = assertDataFrame #' @export #' @include makeTest.R #' @rdname checkDataFrame testDataFrame = makeTestFunction(checkDataFrame) #' @export #' @rdname checkDataFrame test_data_frame = testDataFrame #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkDataFrame expect_data_frame = makeExpectationFunction(checkDataFrame) checkmate/R/checkPathForOutput.R0000644000176200001440000000377613117521473016325 0ustar liggesusers#' @title Check if a path is suited for creating an output file #' #' @description #' Check if a file path can be safely be used to create a file and write to it. #' #' This is checked: #' \itemize{ #' \item{Does \code{dirname(x)} exist?} #' \item{Does no file under path \code{x} exist?} #' \item{Is \code{dirname(x)} writable?} #' } #' Paths are relative to the current working directory. #' #' @templateVar fn PathForOutput #' @template x #' @param overwrite [\code{logical(1)}]\cr #' If \code{TRUE}, an existing file in place is allowed if it #' it is both readable and writable. #' Default is \code{FALSE}. #' @template checker #' @family filesystem #' @export #' @examples #' # Can we create a file in the tempdir? #' testPathForOutput(file.path(tempdir(), "process.log")) checkPathForOutput = function(x, overwrite = FALSE) { if (!qtest(x, "S+")) return("No path provided") qassert(overwrite, "B1") x = normalizePath(x, mustWork = FALSE) dn = dirname(x) w = wf(!dir.exists(dn)) if (length(w) > 0L) return(sprintf("Path to file (dirname) does not exist: '%s' of '%s'", dn[w], x[w])) w = which(file.exists(x)) if (length(w) > 0L) { if (overwrite) return(checkAccess(dn, "w") %and% checkAccess(x[w], "rw")) return(sprintf("File at path already exists: '%s'", x[w])) } return(checkAccess(dn, "w")) } #' @export #' @rdname checkPathForOutput check_path_for_output = checkPathForOutput #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkPathForOutput assertPathForOutput = makeAssertionFunction(checkPathForOutput) #' @export #' @rdname checkPathForOutput assert_path_for_output = assertPathForOutput #' @export #' @include makeTest.R #' @rdname checkPathForOutput testPathForOutput = makeTestFunction(checkPathForOutput) #' @export #' @rdname checkPathForOutput test_path_for_output = testPathForOutput #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkPathForOutput expect_path_for_output = makeExpectationFunction(checkPathForOutput) checkmate/R/checkNull.R0000644000176200001440000000151012762010266014431 0ustar liggesusers#' Check if an argument is NULL #' #' @templateVar fn Null #' @template x #' @template checker #' @family basetypes #' @export #' @examples #' testNull(NULL) #' testNull(1) checkNull = function(x) { if (!is.null(x)) return("Must be NULL") return(TRUE) } #' @export #' @rdname checkNull check_null = checkNull #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkNull assertNull = makeAssertionFunction(checkNull) #' @export #' @rdname checkNull assert_null = assertNull #' @export #' @include makeTest.R #' @rdname checkNull testNull = makeTestFunction(checkNull) #' @export #' @rdname checkNull test_null = testNull # This function is already provided by testthat # #' @export # #' @include makeExpectation.R # #' @template expect # #' @rdname checkNull expect_null = makeExpectationFunction(checkNull) checkmate/R/checkFunction.R0000644000176200001440000000501313007055223015301 0ustar liggesusers#' Check if an argument is a function #' #' @templateVar fn Function #' @template x #' @param args [\code{character}]\cr #' Expected formal arguments. Checks that a function has no arguments if #' set to \code{character(0)}. #' Default is \code{NULL} (no check). #' @param ordered [\code{logical(1)}]\cr #' Flag whether the arguments provided in \code{args} must be the first #' \code{length(args)} arguments of the function in the specified order. #' Default is \code{FALSE}. #' @param nargs [\code{integer(1)}]\cr #' Required number of arguments, without \code{...}. #' Default is \code{NULL} (no check). #' @template null.ok #' @template checker #' @family basetypes #' @export #' @examples #' testFunction(mean) #' testFunction(mean, args = "x") checkFunction = function(x, args = NULL, ordered = FALSE, nargs = NULL, null.ok = FALSE) { qassert(null.ok, "B1") if (is.null(x)) { if (null.ok) return(TRUE) return("Must be a function, not 'NULL'") } if (!is.function(x)) return(sprintf("Must be a function%s, not '%s'", if (null.ok) " (or 'NULL')" else "", guessType(x))) if (!is.null(args)) { qassert(args, "S") fargs = names(formals(x)) %??% character(0L) if (length(args) == 0L) { if (length(fargs) > 0L) return("May not have any arguments") return(TRUE) } qassert(ordered, "B1") if (ordered) { if (any(args != head(fargs, length(args)))) { return(sprintf("Must have first formal arguments (ordered): %s", paste0(args, collapse = ","))) } } else { tmp = setdiff(args, fargs) if (length(tmp)) return(sprintf("Must have formal arguments: %s", paste0(tmp, collapse = ","))) } } if (!is.null(nargs)) { nargs = asCount(nargs) fnargs = length(setdiff(names(formals(x)) %??% character(0L), "...")) if (nargs != fnargs) return(sprintf("Must have exactly %i formal arguments, but has %i", nargs, fnargs)) } return(TRUE) } #' @export #' @rdname checkFunction check_function = checkFunction #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkFunction assertFunction = makeAssertionFunction(checkFunction) #' @export #' @rdname checkFunction assert_function = assertFunction #' @export #' @include makeTest.R #' @rdname checkFunction testFunction = makeTestFunction(checkFunction) #' @export #' @rdname checkFunction test_function = testFunction #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkFunction expect_function = makeExpectationFunction(checkFunction) checkmate/R/checkFALSE.R0000644000176200001440000000150013007055223014343 0ustar liggesusers#' Check if an argument is FALSE #' #' @description #' Simply checks if an argument is \code{FALSE}. #' #' @templateVar fn FALSE. #' @template x #' @template na.ok #' @template checker #' @export #' @examples #' testFALSE(FALSE) #' testFALSE(TRUE) checkFALSE = function(x, na.ok = FALSE) { qassert(na.ok, "B1") if (identical(x, FALSE) || (na.ok && length(x) == 1L && is.na(x))) return(TRUE) return("Must be FALSE") } #' @export #' @rdname checkFALSE check_false = checkFALSE #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkFALSE assertFALSE = makeAssertionFunction(checkFALSE) #' @export #' @rdname checkFALSE assert_false = assertFALSE #' @export #' @include makeTest.R #' @rdname checkFALSE testFALSE = makeTestFunction(checkFALSE) #' @export #' @rdname checkFALSE test_false = testFALSE checkmate/R/checkVector.R0000644000176200001440000000440512762010266014767 0ustar liggesusers#' Check if an argument is a vector #' #' @templateVar fn Vector #' @template x #' @param strict [\code{logical(1)}]\cr #' May the vector have additional attributes or perform a #' check for additional attributes like \code{\link[base]{is.vector}}? #' Default is \code{FALSE} which allows e.g. \code{factor}s or \code{data.frame}s #' to be recognized as vectors. #' @param any.missing [\code{logical(1)}]\cr #' Are vectors with missing values allowed? Default is \code{TRUE}. #' @param all.missing [\code{logical(1)}]\cr #' Are vectors with only missing values allowed? Default is \code{TRUE}. #' @param len [\code{integer(1)}]\cr #' Exact expected length of \code{x}. #' @param min.len [\code{integer(1)}]\cr #' Minimal length of \code{x}. #' @param max.len [\code{integer(1)}]\cr #' Maximal length of \code{x}. #' @param unique [\code{logical(1)}]\cr #' Must all values be unique? Default is \code{FALSE}. #' @param names [\code{character(1)}]\cr #' Check for names. See \code{\link{checkNamed}} for possible values. #' Default is \dQuote{any} which performs no check at all. #' Note that you can use \code{\link{checkSubset}} to check for a specific set of names. #' @template null.ok #' @template checker #' @family basetypes #' @family atomicvector #' @useDynLib checkmate c_check_vector #' @export #' @examples #' testVector(letters, min.len = 1L, any.missing = FALSE) checkVector = function(x, strict = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) { .Call(c_check_vector, x, strict, any.missing, all.missing, len, min.len, max.len, unique, names, null.ok) } #' @export #' @rdname checkVector check_vector = checkVector #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkVector assertVector = makeAssertionFunction(checkVector, c.fun = "c_check_vector") #' @export #' @rdname checkVector assert_vector = assertVector #' @export #' @include makeTest.R #' @rdname checkVector testVector = makeTestFunction(checkVector, c.fun = "c_check_vector") #' @export #' @rdname checkVector test_vector = testVector #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkVector expect_vector = makeExpectationFunction(checkVector, c.fun = "c_check_vector") checkmate/R/checkPOSIXct.R0000644000176200001440000000321013167637071014760 0ustar liggesusers#' @title Check that an argument is a date/time object in POSIXct format #' #' @description #' Checks that an object is of class \code{\link[base]{POSIXct}}. #' #' @templateVar fn Atomic #' @template x #' @param lower [\code{\link[base]{Date}}]\cr #' All non-missing dates in \code{x} must be >= this POSIXct time. Must be provided in the same timezone as \code{x}. #' @param upper [\code{\link[base]{Date}}]\cr #' All non-missing dates in \code{x} must be <= this POSIXct time. Must be provided in the same timezone as \code{x}. #' @template sorted #' @template null.ok #' @inheritParams checkVector #' @template checker #' @family basetypes #' @export #' @useDynLib checkmate c_check_posixct #' @export checkPOSIXct = function(x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, null.ok = FALSE) { .Call(c_check_posixct, x, lower, upper, any.missing, all.missing, len, min.len, max.len, unique, sorted, null.ok) } #' @export #' @rdname checkPOSIXct check_posixct = checkPOSIXct #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkPOSIXct assertPOSIXct = makeAssertionFunction(checkPOSIXct, c.fun = "c_check_posixct") #' @export #' @rdname checkPOSIXct assert_posixct = assertPOSIXct #' @export #' @include makeTest.R #' @rdname checkPOSIXct testPOSIXct = makeTestFunction(checkPOSIXct, c.fun = "c_check_posixct") #' @export #' @rdname checkPOSIXct test_posixct = testPOSIXct #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkPOSIXct expect_posixct = makeExpectationFunction(checkPOSIXct, c.fun = "c_check_posixct") checkmate/R/qassertr.R0000644000176200001440000000453713051012510014363 0ustar liggesusers#' @title Quick recursive arguments checks on lists and data frames #' #' @description #' These functions are the tuned counterparts of \code{\link{qtest}}, #' \code{\link{qassert}} and \code{\link{qexpect}} tailored for recursive #' checks of list elements or data frame columns. #' #' @param x [\code{list} or \code{data.frame}]\cr #' List or data frame to check for compliance with at least one of \code{rules}. #' See details of \code{\link{qtest}} for rule explanation. #' @param rules [\code{character}]\cr #' Set of rules. See \code{\link{qtest}} #' @template var.name #' @return See \code{\link{qassert}}. #' @seealso \code{\link{qtest}}, \code{\link{qassert}} #' @useDynLib checkmate c_qassert #' @export #' @examples #' # All list elements are integers with length >= 1? #' qtestr(as.list(1:10), "i+") #' #' # All list elements (i.e. data frame columns) are numeric? #' qtestr(iris, "n") #' #' # All list elements are numeric, w/o NAs? #' qtestr(list(a = 1:3, b = rnorm(1), c = letters), "N+") #' #' # All list elements are numeric OR character #' qtestr(list(a = 1:3, b = rnorm(1), c = letters), c("N+", "S+")) qassertr = function(x, rules, .var.name = vname(x)) { res = .Call(c_qassert, x, rules, TRUE) if (!identical(res, TRUE)) mstop(qrmsg(x, res, .var.name)) invisible(x) } #' @rdname qassertr #' @param depth [\code{integer(1)}]\cr #' Maximum recursion depth. Defaults to \dQuote{1} to directly check list elements or #' data frame columns. Set to a higher value to check lists of lists of elements. #' @useDynLib checkmate c_qtest #' @export qtestr = function(x, rules, depth = 1L) { .Call(c_qtest, x, rules, TRUE, depth) } #' @rdname qassertr #' @template expect #' @include makeExpectation.R #' @useDynLib checkmate c_qassert #' @export qexpectr = function(x, rules, info = NULL, label = vname(x)) { res = .Call(c_qassert, x, rules, TRUE) if (!identical(res, TRUE)) res = qrmsg(x, res, label) makeExpectation(x, res, info = info, label = label) } qrmsg = function(x, msg, var.name) { pos = attr(msg, "pos") if (testNamed(x)) { item = sprintf(", element '%s' (%i),", names(x)[pos], pos) } else { item = sprintf(", element %i,", pos) } if (length(msg) > 1L) msg = paste0(c("One of the following must apply:", strwrap(msg, prefix = " * ")), collapse = "\n") sprintf("Assertion on '%s'%s failed. %s.", var.name, item, msg) } checkmate/R/checkNamed.R0000644000176200001440000000320413114227470014544 0ustar liggesusers#' Check if an argument is named #' #' @templateVar fn Named #' @template x #' @param type [character(1)]\cr #' Select the check(s) to perform. #' \dQuote{unnamed} checks \code{x} to be unnamed. #' \dQuote{named} (default) checks \code{x} to be named which excludes names to be \code{NA} or empty (\code{""}). #' \dQuote{unique} additionally tests for non-duplicated names. #' \dQuote{strict} checks for unique names which comply to R's variable name restrictions. #' Note that for zero-length \code{x} every name check evaluates to \code{TRUE}. #' @template checker #' @note #' These function are deprecated and will be removed in a future version. #' Please use \code{\link{checkNames}} instead. #' @useDynLib checkmate c_check_named #' @family attributes #' @export #' @examples #' x = 1:3 #' testNamed(x, "unnamed") #' names(x) = letters[1:3] #' testNamed(x, "unique") checkNamed = function(x, type = "named") { .Deprecated("checkNames", "checkmate") .Call(c_check_named, x, type) } #' @export #' @rdname checkNamed check_named = checkNamed #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkNamed assertNamed = makeAssertionFunction(checkNamed, c.fun = "c_check_named") #' @export #' @rdname checkNamed assert_named = assertNamed #' @export #' @include makeTest.R #' @rdname checkNamed testNamed = makeTestFunction(checkNamed, c.fun = "c_check_named") #' @export #' @rdname checkNamed test_named = testNamed # This function is already provided by testthat # #' @export # #' @include makeExpectation.R # #' @template expect # #' @rdname checkNamed expect_named = makeExpectationFunction(checkNamed, c.fun = "c_check_named") checkmate/R/checkFlag.R0000644000176200001440000000201312762010266014367 0ustar liggesusers#' Check if an argument is a flag #' #' @description #' A flag is defined as single logical value. #' #' @templateVar fn Flag #' @template x #' @template na-handling #' @template na.ok #' @template null.ok #' @template checker #' @family scalars #' @useDynLib checkmate c_check_flag #' @export #' @examples #' testFlag(TRUE) #' testFlag(1) checkFlag = function(x, na.ok = FALSE, null.ok = FALSE) { .Call(c_check_flag, x, na.ok, null.ok) } #' @export #' @rdname checkFlag check_flag = checkFlag #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkFlag assertFlag = makeAssertionFunction(checkFlag, c.fun = "c_check_flag") #' @export #' @rdname checkFlag assert_flag = assertFlag #' @export #' @include makeTest.R #' @rdname checkFlag testFlag = makeTestFunction(checkFlag, c.fun = "c_check_flag") #' @export #' @rdname checkFlag test_flag = testFlag #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkFlag expect_flag = makeExpectationFunction(checkFlag, c.fun = "c_check_flag") checkmate/R/checkDirectoryExists.R0000644000176200001440000000405512762010266016672 0ustar liggesusers#' Check for existence and access rights of directories #' #' @note #' The functions without the suffix \dQuote{exists} are deprecated and will be removed #' from the package in a future version due to name clashes. #' #' @templateVar fn DirectoryExists #' @template x #' @inheritParams checkAccess #' @inheritParams checkFile #' @template checker #' @family filesystem #' @export #' @examples #' # Is R's home directory readable? #' testDirectory(R.home(), "r") #' #' # Is R's home directory readable and writable? #' testDirectory(R.home(), "rw") checkDirectoryExists = function(x, access = "") { if (!qtest(x, "S+")) return("No directory provided") w = wf(!file.exists(x)) if (length(w) > 0L) return(sprintf("Directory '%s' does not exists", x[w])) w = wf(!dir.exists(x)) if (length(w) > 0L) return(sprintf("Directory expected, but file in place: '%s'", x[w])) checkAccess(x, access) } #' @export #' @rdname checkDirectoryExists check_directory_exists = checkDirectoryExists #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkDirectoryExists assertDirectoryExists = makeAssertionFunction(checkDirectoryExists) #' @export #' @rdname checkDirectoryExists assert_directory_exists = assertDirectoryExists #' @export #' @include makeTest.R #' @rdname checkDirectoryExists testDirectoryExists = makeTestFunction(checkDirectoryExists) #' @export #' @rdname checkDirectoryExists test_directory_exists = testDirectoryExists #' @export #' @rdname checkDirectoryExists expect_directory_exists = makeExpectationFunction(checkDirectoryExists) #' @export #' @rdname checkDirectoryExists checkDirectory = checkDirectoryExists #' @export #' @rdname checkDirectoryExists assertDirectory = assertDirectoryExists #' @export #' @rdname checkDirectoryExists assert_directory = assert_directory_exists #' @export #' @rdname checkDirectoryExists testDirectory = testDirectoryExists #' @export #' @rdname checkDirectoryExists test_directory = test_directory_exists #' @export #' @rdname checkDirectoryExists expect_directory = expect_directory_exists checkmate/R/checkDate.R0000644000176200001440000000451213167637071014412 0ustar liggesusers#' @title Check that an argument is a Date #' #' @description #' Checks that an object is of class \code{\link[base]{Date}}. #' #' @templateVar fn Atomic #' @template x #' @param lower [\code{\link[base]{Date}}]\cr #' All non-missing dates in \code{x} must be >= this date. Comparison is done via \code{\link[base]{Ops.Date}}. #' @param upper [\code{\link[base]{Date}}]\cr #' All non-missing dates in \code{x} must be before <= this date. Comparison is done via \code{\link[base]{Ops.Date}}. #' @template null.ok #' @inheritParams checkVector #' @template checker #' @family basetypes #' @export checkDate = function(x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, null.ok = FALSE) { qassert(null.ok, "B1") if (is.null(x)) { if (null.ok) return(TRUE) return("Must be of class 'Date', not 'NULL'") } if (!inherits(x, "Date")) return(sprintf("Must be of class 'Date'%s, not '%s'", if (null.ok) " (or 'NULL')" else "", guessType(x))) checkInteger(as.integer(x), any.missing = any.missing, all.missing = all.missing, len = len, min.len = min.len, max.len = max.len, unique = unique) %and% checkDateBounds(x, lower, upper) } checkDateBounds = function(x, lower, upper) { if (!is.null(lower)) { lower = as.Date(lower, origin = "1970-01-01") if (length(lower) != 1L || is.na(lower)) stop("Argument 'lower' must be a single (non-missing) date") if (any(x[!is.na(x)] < lower)) return(sprintf("Date must be >= %s", lower)) } if (!is.null(upper)) { upper = as.Date(upper, origin = "1970-01-01") if (length(upper) != 1L || is.na(upper)) stop("Argument 'upper' must be a single (non-missing) date") if (any(x[!is.na(x)] > upper)) return(sprintf("Date must be <= %s", upper)) } return(TRUE) } #' @export #' @rdname checkDate check_date = checkDate #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkDate assertDate = makeAssertionFunction(checkDate) #' @export #' @rdname checkDate assert_date = assertDate #' @export #' @include makeTest.R #' @rdname checkDate testDate = makeTestFunction(checkDate) #' @export #' @rdname checkDate test_date = testDate #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkDate expect_date = makeExpectationFunction(checkDate) checkmate/R/checkString.R0000644000176200001440000000226013145532277014777 0ustar liggesusers#' Check if an argument is a string #' #' @description #' A string is defined as a scalar character vector. #' #' @templateVar fn String #' @template x #' @template na-handling #' @template na.ok #' @inheritParams checkCharacter #' @template null.ok #' @template checker #' @family scalars #' @export #' @useDynLib checkmate c_check_string #' @examples #' testString("a") #' testString(letters) checkString = function(x, na.ok = FALSE, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE) { .Call(c_check_string, x, na.ok, min.chars, null.ok) %and% checkCharacterPattern(x, pattern, fixed, ignore.case) } #' @export #' @rdname checkString check_string = checkString #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkString assertString = makeAssertionFunction(checkString) #' @export #' @rdname checkString assert_string = assertString #' @export #' @include makeTest.R #' @rdname checkString testString = makeTestFunction(checkString) #' @export #' @rdname checkString test_string = testString #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkString expect_string = makeExpectationFunction(checkString) checkmate/R/checkClass.R0000644000176200001440000000414313160423672014573 0ustar liggesusers#' Check the class membership of an argument #' #' @templateVar fn Class #' @template x #' @param classes [\code{character}]\cr #' Class names to check for inheritance with \code{\link[base]{inherits}}. #' @param ordered [\code{logical(1)}]\cr #' Expect \code{x} to be specialized in provided order. #' Default is \code{FALSE}. #' @template null.ok #' @template checker #' @family attributes #' @seealso \code{\link{checkR6}} #' @export #' @examples #' # Create an object with classes "foo" and "bar" #' x = 1 #' class(x) = c("foo", "bar") #' #' # is x of class "foo"? #' testClass(x, "foo") #' #' # is x of class "foo" and "bar"? #' testClass(x, c("foo", "bar")) #' #' # is x of class "foo" or "bar"? #' \dontrun{ #' assert( #' checkClass(x, "foo"), #' checkClass(x, "bar") #' ) #' } #' # is x most specialized as "bar"? #' testClass(x, "bar", ordered = TRUE) checkClass = function(x, classes, ordered = FALSE, null.ok = FALSE) { qassert(classes, "S+") qassert(ordered, "B1") qassert(null.ok, "B1") if (is.null(x) && null.ok) return(TRUE) ord = inherits(x, classes, TRUE) w = wf(ord == 0L) if (length(w) > 0L) { cl = class(x) return(sprintf("Must have class '%s', but has class%s '%s'", classes[w], if (length(cl) > 1L) "es" else "", paste0(cl, collapse = "','"))) } if (ordered) { w = wf(ord != seq_along(ord)) if (length(w) > 0L) { cl = class(x) return(sprintf("Must have class '%s' in position %i, but has class%s '%s'", classes[w], w, if (length(cl) > 1L) "es" else "", paste0(cl, collapse = "','"))) } } return(TRUE) } #' @export #' @rdname checkClass check_class = checkClass #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkClass assertClass = makeAssertionFunction(checkClass) #' @export #' @rdname checkClass assert_class = assertClass #' @export #' @include makeTest.R #' @rdname checkClass testClass = makeTestFunction(checkClass) #' @export #' @rdname checkClass test_class = testClass #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkClass expect_class = makeExpectationFunction(checkClass) checkmate/R/helper.R0000644000176200001440000000102413171647657014017 0ustar liggesusersmstop = function(msg, ...) { stop(simpleError(sprintf(msg, ...), sys.call(1L))) } "%and%" = function(lhs, rhs) { if (identical(lhs, TRUE)) rhs else lhs } "%nin%" = function(x, y) { !match(x, y, nomatch = 0L) } convertCamelCase = function(x) { tolower(gsub("((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))", "_\\1", x, perl = TRUE)) } #' @useDynLib checkmate c_guess_type guessType = function(x) { .Call(c_guess_type, x) } isSameType = function(x, y) { identical(typeof(x), typeof(y)) || (is.numeric(x) && is.numeric(y)) } checkmate/R/checkNames.R0000644000176200001440000000747513154204617014603 0ustar liggesusers#' Check names to comply to specific rules #' #' @description #' Similar to \code{\link{checkNamed}} but you can pass the names directly. #' #' @templateVar fn Named #' @param x [\code{character} || \code{NULL}]\cr #' Names to check using rules defined via \code{type}. #' @param type [character(1)]\cr #' Type of formal check(s) to perform on the names. #' \describe{ #' \item{unnamed:}{Checks \code{x} to be \code{NULL}.} #' \item{named:}{Checks \code{x} for regular names which excludes names to be \code{NA} or empty (\code{""}).} #' \item{unique:}{Performs checks like with \dQuote{named} and additionally tests for non-duplicated names.} #' \item{strict:}{Performs checks like with \dQuote{unique} and additionally fails for names with UTF-8 characters and names which do not comply to R's variable name restrictions. As regular expression, this is \dQuote{^[.]*[a-zA-Z]+[a-zA-Z0-9._]*$}.} #' } #' Note that for zero-length \code{x}, all these name checks evaluate to \code{TRUE}. #' @param subset.of [\code{character}]\cr #' Names provided in \code{x} must be subset of the set \code{subset.of}. #' @param must.include [\code{character}]\cr #' Names provided in \code{x} must be a superset of the set \code{must.include}. #' @param permutation.of [\code{character}]\cr #' Names provided in \code{x} must be a permutation of the set \code{permutation.of}. #' Duplicated names in \code{permutation.of} are stripped out and duplicated names in \code{x} #' thus lead to a failed check. #' Use this argument instead of \code{identical.to} if the order of the names is not relevant. #' @param identical.to [\code{character}]\cr #' Names provided in \code{x} must be identical to the vector \code{identical.to}. #' Use this argument instead of \code{permutation.of} if the order of the names is relevant. #' @template checker #' @useDynLib checkmate c_check_names #' @family attributes #' @export #' @examples #' x = 1:3 #' testNames(x, "unnamed") #' names(x) = letters[1:3] #' testNames(x, "unique") #' #' cn = c("Species", "Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width") #' assertNames(names(iris), permutation.of = cn) checkNames = function(x, type = "named", subset.of = NULL, must.include = NULL, permutation.of = NULL, identical.to = NULL) { .Call(c_check_names, x, type) %and% checkNamesCmp(x, subset.of, must.include, permutation.of, identical.to) } checkNamesCmp = function(x, subset.of, must.include, permutation.of, identical.to) { if (!is.null(subset.of)) { qassert(subset.of, "S") if (anyMissing(match(x, subset.of))) return(sprintf("Must be a subset of set {%s}", paste0(subset.of, collapse = ","))) } if (!is.null(must.include)) { qassert(must.include, "S") if (anyMissing(match(must.include, x))) return(sprintf("Must include the elements {%s}", paste0(must.include, collapse = ","))) } if (!is.null(permutation.of)) { permutation.of = unique(qassert(permutation.of, "S")) if (length(x) != length(permutation.of) || !setequal(x, permutation.of)) return(sprintf("Must be a permutation of set {%s}", paste0(permutation.of, collapse = ","))) } if (!is.null(identical.to)) { qassert(identical.to, "S") if (!identical(x, identical.to)) return(sprintf("Must be a identical to (%s)", paste0(identical.to, collapse = ","))) } return(TRUE) } #' @export #' @rdname checkNames check_names = checkNames #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkNames assertNames = makeAssertionFunction(checkNames) #' @export #' @rdname checkNames assert_names = assertNames #' @export #' @include makeTest.R #' @rdname checkNames testNames = makeTestFunction(checkNames) #' @export #' @rdname checkNames test_names = testNames #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkNames expect_names = makeExpectationFunction(checkNames) checkmate/R/allMissing.R0000644000176200001440000000054013043465157014633 0ustar liggesusers#' @rdname anyMissing #' @useDynLib checkmate c_all_missing #' @export #' @examples #' allMissing(1:2) #' allMissing(c(1, NA)) #' allMissing(c(NA, NA)) #' x = data.frame(a = 1:2, b = NA) #' # Note how allMissing combines the results for data frames: #' allMissing(x) #' all(sapply(x, allMissing)) allMissing = function(x) { .Call(c_all_missing, x) } checkmate/R/checkTibble.R0000644000176200001440000000314313162134131014715 0ustar liggesusers#' Check if an argument is a tibble #' #' @templateVar fn Tibble #' @template x #' @inheritParams checkMatrix #' @inheritParams checkList #' @inheritParams checkDataFrame #' @template null.ok #' @template checker #' @family compound #' @export #' @examples #' library(tibble) #' x = as_tibble(iris) #' testTibble(x) #' testTibble(x, nrow = 150, any.missing = FALSE) checkTibble = function(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) { if (!requireNamespace("tibble", quietly = TRUE)) stop("Install package 'tibble' to perform checks of tibbles") qassert(null.ok, "B1") if (is.null(x)) { if (null.ok) return(TRUE) return("Must be a tibble, not 'NULL'") } if (!tibble::is_tibble(x)) return(paste0("Must be a tibble", if (null.ok) " (or 'NULL')" else "", sprintf(", not %s", guessType(x)))) checkDataFrame(x, types, any.missing, all.missing, min.rows, min.cols, nrows, ncols, row.names, col.names, null.ok) } #' @export #' @rdname checkTibble check_tibble = checkTibble #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkTibble assertTibble = makeAssertionFunction(checkTibble) #' @export #' @rdname checkTibble assert_tibble = assertTibble #' @export #' @include makeTest.R #' @rdname checkTibble testTibble = makeTestFunction(checkTibble) #' @export #' @rdname checkTibble test_tibble = testTibble #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkTibble expect_tibble = makeExpectationFunction(checkTibble) checkmate/R/checkChoice.R0000644000176200001440000000361513170103134014710 0ustar liggesusers#' Check if an object is an element of a given set #' #' @templateVar fn Choice #' @template x #' @param choices [\code{atomic}]\cr #' Set of possible values. #' @template null.ok #' @template fmatch #' @template checker #' @template set #' @family set #' @export #' @examples #' testChoice("x", letters) #' #' # x is not converted before the comparison (except for numerics) #' testChoice(factor("a"), "a") #' testChoice(1, "1") #' testChoice(1, as.integer(1)) checkChoice = function(x, choices, null.ok = FALSE, fmatch = FALSE) { qassert(null.ok, "B1") if (is.null(x)) { if (null.ok) return(TRUE) qassert(choices, "a") return(sprintf("Must be a subset of {'%s'}, not 'NULL'", paste0(choices, collapse = "','"))) } qassert(choices, "a") if (!qtest(x, "a1")) return(sprintf("Must be element of set {'%s'}, but is not atomic scalar", paste0(unique(choices), collapse = "','"))) if (!isSameType(x, choices)) return(sprintf("Must be element of set {'%s'}, but types do not match (%s != %s)", paste0(unique(choices), collapse = "','"), class(x)[1L], class(choices)[1L])) if (isTRUE(fmatch) && requireNamespace("fastmatch", quietly = TRUE)) match = fastmatch::fmatch if (match(x, choices, 0L) == 0L) return(sprintf("Must be element of set {'%s'}, but is '%s'", paste0(unique(choices), collapse = "','"), x)) return(TRUE) } #' @export #' @rdname checkChoice check_choice = checkChoice #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkChoice assertChoice = makeAssertionFunction(checkChoice) #' @export #' @rdname checkChoice assert_choice = assertChoice #' @export #' @include makeTest.R #' @rdname checkChoice testChoice = makeTestFunction(checkChoice) #' @export #' @rdname checkChoice test_choice = testChoice #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkChoice expect_choice = makeExpectationFunction(checkChoice) checkmate/R/checkMatrix.R0000644000176200001440000000441612762010266014773 0ustar liggesusers#' Check if an argument is a matrix #' #' @templateVar fn Matrix #' @template x #' @template mode #' @param any.missing [\code{logical(1)}]\cr #' Are missing values allowed? Default is \code{TRUE}. #' @param all.missing [\code{logical(1)}]\cr #' Are matrices with only missing values allowed? Default is \code{TRUE}. #' @param min.rows [\code{integer(1)}]\cr #' Minimum number of rows. #' @param min.cols [\code{integer(1)}]\cr #' Minimum number of columns. #' @param nrows [\code{integer(1)}]\cr #' Exact number of rows. #' @param ncols [\code{integer(1)}]\cr #' Exact number of columns. #' @param row.names [\code{character(1)}]\cr #' Check for row names. Default is \dQuote{NULL} (no check). #' See \code{\link{checkNamed}} for possible values. #' Note that you can use \code{\link{checkSubset}} to check for a specific set of names. #' @param col.names [\code{character(1)}]\cr #' Check for column names. Default is \dQuote{NULL} (no check). #' See \code{\link{checkNamed}} for possible values. #' Note that you can use \code{\link{checkSubset}} to test for a specific set of names. #' @template null.ok #' @template checker #' @family basetypes #' @family compound #' @useDynLib checkmate c_check_matrix #' @export #' @examples #' x = matrix(1:9, 3) #' colnames(x) = letters[1:3] #' testMatrix(x, nrows = 3, min.cols = 1, col.names = "named") checkMatrix = function(x, mode = NULL, any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) { .Call(c_check_matrix, x, mode, any.missing, all.missing, min.rows, min.cols, nrows, ncols, row.names, col.names, null.ok) } #' @export #' @rdname checkMatrix check_matrix = checkMatrix #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkMatrix assertMatrix = makeAssertionFunction(checkMatrix, c.fun = "c_check_matrix") #' @export #' @rdname checkMatrix assert_matrix = assertMatrix #' @export #' @include makeTest.R #' @rdname checkMatrix testMatrix = makeTestFunction(checkMatrix, c.fun = "c_check_matrix") #' @export #' @rdname checkMatrix test_matrix = testMatrix #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkMatrix expect_matrix = makeExpectationFunction(checkMatrix, c.fun = "c_check_matrix") checkmate/R/checkOS.R0000644000176200001440000000230313006323271014034 0ustar liggesusers#' Check the operating system #' #' @templateVar fn OS #' @param os [\code{character(1)}]\cr #' Check the operating system to be in a set with possible elements \dQuote{windows}, #' \dQuote{mac}, \dQuote{linux} and \dQuote{solaris}. #' @template checker #' @export #' @examples #' testOS("linux") checkOS = function(os) { ok = match.arg(os, c("windows", "mac", "linux", "solaris"), several.ok = TRUE) if (checkmate$os %nin% ok) return(sprintf("OS must be %s", paste0(ok, collapse = " or "))) return(TRUE) } #' @export #' @rdname checkOS check_os = checkOS #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkOS assertOS = function(os, add = NULL, .var.name = NULL) { res = checkOS(os) makeAssertion(os, res, .var.name %??% "Operating System", add) } #' @export #' @rdname checkOS assert_os = assertOS #' @export #' @include makeTest.R #' @rdname checkOS testOS = makeTestFunction(checkOS) #' @export #' @rdname checkOS test_os = testOS #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkOS expect_os = function(os, info = NULL, label = NULL) { res = checkOS(os) makeExpectation(checkmate$os, res, info, label = label %??% "Operating System") } checkmate/R/checkInteger.R0000644000176200001440000000263713064452167015135 0ustar liggesusers#' Check if an argument is vector of type integer #' #' @templateVar fn Integer #' @template x #' @template na-handling #' @inheritParams checkVector #' @template bounds #' @template sorted #' @template null.ok #' @template checker #' @family basetypes #' @seealso \code{\link{asInteger}} #' @useDynLib checkmate c_check_integer #' @export #' @examples #' testInteger(1L) #' testInteger(1.) #' testInteger(1:2, lower = 1, upper = 2, any.missing = FALSE) checkInteger = function(x, lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) { .Call(c_check_integer, x, lower, upper, any.missing, all.missing, len, min.len, max.len, unique, sorted, names, null.ok) } #' @export #' @rdname checkInteger check_integer = checkInteger #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkInteger assertInteger = makeAssertionFunction(checkInteger, c.fun = "c_check_integer") #' @export #' @rdname checkInteger assert_integer = assertInteger #' @export #' @include makeTest.R #' @rdname checkInteger testInteger = makeTestFunction(checkInteger, c.fun = "c_check_integer") #' @export #' @rdname checkInteger test_integer = testInteger #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkInteger expect_integer = makeExpectationFunction(checkInteger, c.fun = "c_check_integer") checkmate/R/checkR6.R0000644000176200001440000000503513171650103014007 0ustar liggesusers#' Check if an argument is a R6 class #' #' @templateVar fn Class #' @template x #' @inheritParams checkClass #' @param cloneable [\code{logical(1)}]\cr #' If \code{TRUE}, check that \code{x} has a \code{clone} method. If \code{FALSE}, ensure that #' \code{x} is not cloneable. #' @param public [\code{character}]\cr #' Names of expected public slots. This includes active bindings. #' @param private [\code{character}]\cr #' Names of expected private slots. #' @template null.ok #' @template checker #' @export #' @examples #' library(R6) #' generator = R6Class("Bar", #' public = list(a = 5), #' private = list(b = 42), #' active = list(c = function() 99) #' ) #' x = generator$new() #' checkR6(x, "Bar", cloneable = TRUE, public = "a") checkR6 = function(x, classes = NULL, ordered = FALSE, cloneable = NULL, public = NULL, private = NULL, null.ok = FALSE) { if (!requireNamespace("R6", quietly = TRUE)) stop("Install package 'R6' to perform checks of R6 classes") if (is.null(x)) { if (null.ok) return(TRUE) return("Must be an R6 class, not 'NULL'") } if (!R6::is.R6(x)) return(paste0("Must be an R6 class", if (null.ok) " (or 'NULL')" else "", sprintf(", not %s", guessType(x)))) checkClass(x, c(classes, "R6"), ordered) %and% checkR6Props(x, cloneable, public, private) } checkR6Props = function(x, cloneable = NULL, public = NULL, private = NULL) { if (!is.null(cloneable)) { qassert(cloneable, "B1") if (cloneable) { if (!exists("clone", envir = x)) return("Must be cloneable") } else { if (exists("clone", envir = x)) return("May not be cloneable") } } if (!is.null(public)) { qassert(public, "S") i = wf(public %nin% ls(x, all.names = TRUE)) if (length(i) > 0L) return(sprintf("Must provide the public slot '%s'", public[i])) } if (!is.null(private)) { qassert(private, "S") i = wf(private %nin% ls(x$.__enclos_env__[["private"]], all.names = TRUE)) if (length(i) > 0L) return(sprintf("Must provide the private slot '%s'", private[i])) } return(TRUE) } #' @export #' @rdname checkR6 check_r6 = checkR6 #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkR6 assertR6 = makeAssertionFunction(checkR6) #' @export #' @rdname checkR6 assert_r6 = assertR6 #' @export #' @include makeTest.R #' @rdname checkR6 testR6 = makeTestFunction(checkR6) #' @export #' @rdname checkR6 test_r6 = testR6 #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkR6 expect_r6 = makeExpectationFunction(checkR6) checkmate/R/checkTRUE.R0000644000176200001440000000145113007055223014275 0ustar liggesusers#' Check if an argument is TRUE #' #' @description #' Simply checks if an argument is \code{TRUE}. #' #' @templateVar fn TRUE. #' @template x #' @template na.ok #' @template checker #' @export #' @examples #' testTRUE(TRUE) #' testTRUE(FALSE) checkTRUE = function(x, na.ok = FALSE) { qassert(na.ok, "B1") if (identical(x, TRUE) || (na.ok && length(x) == 1L && is.na(x))) return(TRUE) return("Must be TRUE") } #' @export #' @rdname checkTRUE check_true = checkTRUE #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkTRUE assertTRUE = makeAssertionFunction(checkTRUE) #' @export #' @rdname checkTRUE assert_true = assertTRUE #' @export #' @include makeTest.R #' @rdname checkTRUE testTRUE = makeTestFunction(checkTRUE) #' @export #' @rdname checkTRUE test_true = testTRUE checkmate/R/checkNumeric.R0000644000176200001440000000272113167111457015132 0ustar liggesusers#' Check that an argument is a vector of type numeric #' #' @templateVar fn Numeric #' @template x #' @template na-handling #' @inheritParams checkVector #' @template bounds #' @template sorted #' @param finite [\code{logical(1)}]\cr #' Check for only finite values? Default is \code{FALSE}. #' @template null.ok #' @template checker #' @family basetypes #' @useDynLib checkmate c_check_numeric #' @export #' @examples #' testNumeric(1) #' testNumeric(1, min.len = 1, lower = 0) checkNumeric = function(x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) { .Call(c_check_numeric, x, lower, upper, finite, any.missing, all.missing, len, min.len, max.len, unique, sorted, names, null.ok) } #' @export #' @rdname checkNumeric check_numeric = checkNumeric #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkNumeric assertNumeric = makeAssertionFunction(checkNumeric, c.fun = "c_check_numeric") #' @export #' @rdname checkNumeric assert_numeric = assertNumeric #' @export #' @include makeTest.R #' @rdname checkNumeric testNumeric = makeTestFunction(checkNumeric, c.fun = "c_check_numeric") #' @export #' @rdname checkNumeric test_numeric = testNumeric #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkNumeric expect_numeric = makeExpectationFunction(checkNumeric, c.fun = "c_check_numeric") checkmate/R/checkFactor.R0000644000176200001440000000674413062216270014750 0ustar liggesusers#' Check if an argument is a factor #' #' @templateVar fn Factor #' @template x #' @inheritParams checkVector #' @param levels [\code{character}]\cr #' Vector of allowed factor levels. #' @param ordered [\code{logical(1)}]\cr #' Check for an ordered factor? If \code{FALSE} or \code{TRUE}, checks explicitly #' for an unordered or ordered factor, respectively. #' Default is \code{NA} which does not perform any additional check. #' @param empty.levels.ok [\code{logical(1)}]\cr #' Are empty levels allowed? #' Default is \code{TRUE}. #' @param n.levels [\code{integer(1)}]\cr #' Exact number of factor levels. #' Default is \code{NULL} (no check). #' @param min.levels [\code{integer(1)}]\cr #' Minimum number of factor levels. #' Default is \code{NULL} (no check). #' @param max.levels [\code{integer(1)}]\cr #' Maximum number of factor levels. #' Default is \code{NULL} (no check). #' @template null.ok #' @template checker #' @family basetypes #' @useDynLib checkmate c_check_factor #' @export #' @examples #' x = factor("a", levels = c("a", "b")) #' testFactor(x) #' testFactor(x, empty.levels.ok = FALSE) checkFactor = function(x, levels = NULL, ordered = NA, empty.levels.ok = TRUE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, n.levels = NULL, min.levels = NULL, max.levels = NULL, unique = FALSE, names = NULL, null.ok = FALSE) { .Call(c_check_factor, x, any.missing, all.missing, len, min.len, max.len, unique, names, null.ok) %and% checkFactorLevels(x, levels, ordered, empty.levels.ok, n.levels, min.levels, max.levels) } checkFactorLevels = function(x , levels = NULL, ordered = NA, empty.levels.ok = TRUE, n.levels = NULL, min.levels = NULL, max.levels = NULL) { if (!is.null(x)) { if (!is.null(levels)) { qassert(levels, "S") if (!setequal(levels(x), levels)) return(sprintf("Must have levels: %s", paste0(levels, collapse = ","))) } qassert(ordered, "b1") if (!is.na(ordered)) { x.ordered = is.ordered(x) if (ordered && !x.ordered) return("Must be an ordered factor, but is unordered") else if (!ordered && x.ordered) return("Must be an unordered factor, but is ordered") } qassert(empty.levels.ok, "B1") if (!empty.levels.ok) { empty = setdiff(levels(x), x) if (length(empty) > 0L) return(sprintf("Has has empty levels '%s'", paste0(empty, collapse = "','"))) } if (!is.null(n.levels)) { qassert(n.levels, "X1") if (length(levels(x)) != n.levels) return(sprintf("Must have exactly %i levels", n.levels)) } if (!is.null(min.levels)) { qassert(min.levels, "X1") if (length(levels(x)) < min.levels) return(sprintf("Must have at least %i levels", min.levels)) } if (!is.null(max.levels)) { qassert(max.levels, "X1") if (length(levels(x)) > max.levels) return(sprintf("Must have at most %i levels", max.levels)) } } return(TRUE) } #' @export #' @rdname checkFactor check_factor = checkFactor #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkFactor assertFactor = makeAssertionFunction(checkFactor) #' @export #' @rdname checkFactor assert_factor = assertFactor #' @export #' @include makeTest.R #' @rdname checkFactor testFactor = makeTestFunction(checkFactor) #' @export #' @rdname checkFactor test_factor = testFactor #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkFactor expect_factor = makeExpectationFunction(checkFactor) checkmate/R/checkEnvironment.R0000644000176200001440000000313713167073256016042 0ustar liggesusers#' Check if an argument is an environment #' #' @templateVar fn Environment #' @template x #' @param contains [\code{character}]\cr #' Vector of object names expected in the environment. #' Defaults to \code{character(0)}. #' @template null.ok #' @template checker #' @family basetypes #' @export #' @examples #' ee = as.environment(list(a = 1)) #' testEnvironment(ee) #' testEnvironment(ee, contains = "a") checkEnvironment = function(x, contains = character(0L), null.ok = FALSE) { qassert(contains, "S") qassert(null.ok, "B1") if (is.null(x)) { if (null.ok) return(TRUE) return("Must be an environment, not 'NULL'") } if (!is.environment(x)) return(sprintf("Must be an environment%s, not '%s'", if (null.ok) " (or 'NULL')" else "", guessType(x))) if (length(contains) > 0L) { w = wf(contains %nin% ls(x, all.names = TRUE)) if (length(w) > 0L) return(sprintf("Must contain an object with name '%s'", contains[w])) } return(TRUE) } #' @export #' @rdname checkEnvironment check_environment = checkEnvironment #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkEnvironment assertEnvironment = makeAssertionFunction(checkEnvironment) #' @export #' @rdname checkEnvironment assert_environment = assertEnvironment #' @export #' @include makeTest.R #' @rdname checkEnvironment testEnvironment = makeTestFunction(checkEnvironment) #' @export #' @rdname checkEnvironment test_environment = testEnvironment #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkEnvironment expect_environment = makeExpectationFunction(checkEnvironment) checkmate/R/anyNaN.R0000644000176200001440000000072112762010266013710 0ustar liggesusers#' Check if an object contains NaN values #' #' @description #' Supported are atomic types (see \code{\link[base]{is.atomic}}), lists and data frames. #' #' @param x [\code{ANY}]\cr #' Object to check. #' @return [\code{logical(1)}] Returns \code{TRUE} if any element is \code{NaN}. #' @useDynLib checkmate c_any_nan #' @export #' @examples #' anyNaN(1:10) #' anyNaN(c(1:10, NaN)) #' iris[3, 3] = NaN #' anyNaN(iris) anyNaN = function(x) { .Call(c_any_nan, x) } checkmate/R/checkScalarNA.R0000644000176200001440000000224013007055223015137 0ustar liggesusers#' Check if an argument is a single missing value #' #' @templateVar fn ScalarNA #' @template x #' @template null.ok #' @template checker #' @family scalars #' @export #' @examples #' testScalarNA(1) #' testScalarNA(NA_real_) #' testScalarNA(rep(NA, 2)) checkScalarNA = function(x, null.ok = FALSE) { qassert(null.ok, "B1") if (is.null(x)) { if (null.ok) return(TRUE) return("Must be a scalar missing value, not 'NULL'") } if (length(x) != 1L || !is.na(x)) return(paste0("Must be a scalar missing value", if (null.ok) " (or 'NULL')" else "")) return(TRUE) } #' @export #' @rdname checkScalarNA check_scalar_na = checkScalarNA #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkScalarNA assertScalarNA = makeAssertionFunction(checkScalarNA) #' @export #' @rdname checkScalarNA assert_scalar_na = assertScalarNA #' @export #' @include makeTest.R #' @rdname checkScalarNA testScalarNA = makeTestFunction(checkScalarNA) #' @export #' @rdname checkScalarNA test_scalar_na = testScalarNA #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkScalarNA expect_scalar_na = makeExpectationFunction(checkScalarNA) checkmate/R/checkArray.R0000644000176200001440000000305612762010266014604 0ustar liggesusers#' Check if an argument is an array #' #' @templateVar fn Array #' @template x #' @template mode #' @param any.missing [\code{logical(1)}]\cr #' Are missing values allowed? Default is \code{TRUE}. #' @param d [\code{integer(1)}]\cr #' Exact number of dimensions of array \code{x}. #' Default is \code{NULL} (no check). #' @param min.d [\code{integer(1)}]\cr #' Minimum number of dimensions of array \code{x}. #' Default is \code{NULL} (no check). #' @param max.d [\code{integer(1)}]\cr #' Maximum number of dimensions of array \code{x}. #' Default is \code{NULL} (no check). #' @template null.ok #' @template checker #' @family basetypes #' @family compound #' @useDynLib checkmate c_check_array #' @export #' @examples #' checkArray(array(1:27, dim = c(3, 3, 3)), d = 3) checkArray = function(x, mode = NULL, any.missing = TRUE, d = NULL, min.d = NULL, max.d = NULL, null.ok = FALSE) { .Call(c_check_array, x, mode, any.missing, d, min.d, max.d, null.ok) } #' @export #' @rdname checkArray check_array = checkArray #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkArray assertArray = makeAssertionFunction(checkArray, c.fun = "c_check_array") #' @export #' @rdname checkArray assert_array = assertArray #' @export #' @include makeTest.R #' @rdname checkArray testArray = makeTestFunction(checkArray, c.fun = "c_check_array") #' @export #' @rdname checkArray test_array = testArray #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkArray expect_array = makeExpectationFunction(checkArray, c.fun = "c_check_array") checkmate/R/checkBit.R0000644000176200001440000000454313162404132014240 0ustar liggesusers#' Check if an argument is a bit vector #' #' @templateVar fn Bit #' @template x #' @inheritParams checkVector #' @param min.0 [\code{integer(1)}]\cr #' Minimum number of elements being \dQuote{0}/\code{FALSE}/off. #' @param min.1 [\code{integer(1)}]\cr #' Minimum number of elements being \dQuote{1}/\code{TRUE}/on. #' @template null.ok #' @template checker #' @export #' @examples #' library(bit) #' x = as.bit(replace(logical(10), sample(10, 5), TRUE)) #' testBit(x, len = 10, min.0 = 1) checkBit = function(x, len = NULL, min.len = NULL, max.len = NULL, min.0 = NULL, min.1 = NULL, null.ok = FALSE) { if (!requireNamespace("bit", quietly = TRUE)) stop("Install package 'bit' to perform checks on bit vectors") qassert(null.ok, "B1") if (is.null(x)) { if (null.ok) return(TRUE) return("Must be a bit, not 'NULL'") } if (!bit::is.bit(x)) return(paste0("Must be a bit", if (null.ok) " (or 'NULL')" else "", sprintf(", not %s", guessType(x)))) n = bit::length.bit(x) if (!is.null(len)) { qassert(len, "X1") if (len != n) return(sprintf("Must have length %i, but has length %i", len, n)) } if (!is.null(min.len)) { qassert(min.len, "X1") if (n < min.len) return(sprintf("Must have length >= %i, but has length %i", min.len, n)) } if (!is.null(max.len)) { qassert(max.len, "X1") if (n > max.len) return(sprintf("Must have length <= %i, but has length %i", max.len, n)) } if (!is.null(min.0) || !is.null(min.1)) { s = bit::sum.bit(x) if (!is.null(min.0)) { qassert(min.0, "X1[0,)") if (n - s < min.0) return(sprintf("Must have at least %i elements being '0', has %i", n, n - s)) } if (!is.null(min.1)) { qassert(min.1, "X1[0,)") if (s < min.1) return(sprintf("Must have at least %i elements being '1', has %i", n, s)) } } return(TRUE) } #' @export #' @rdname checkBit check_bit = checkBit #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkBit assertBit = makeAssertionFunction(checkBit) #' @export #' @rdname checkBit assert_bit = assertBit #' @export #' @include makeTest.R #' @rdname checkBit testBit = makeTestFunction(checkBit) #' @export #' @rdname checkBit test_bit = testBit #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkBit expect_bit = makeExpectationFunction(checkBit) checkmate/R/zzz.R0000644000176200001440000000723213171647572013400 0ustar liggesusers#' @description #' #' \describe{ #' \item{Homepage:}{\url{https://github.com/mllg/checkmate}} #' \item{Bug Reports:}{\url{https://github.com/mllg/checkmate/issues}} #' } #' #' @section Overview of implemented functions: #' #' Check scalars: #' \itemize{ #' \item{\code{\link{checkFlag}}} #' \item{\code{\link{checkCount}}} #' \item{\code{\link{checkNumber}}} #' \item{\code{\link{checkInt}}} #' \item{\code{\link{checkString}}} #' \item{\code{\link{checkScalar}}} #' \item{\code{\link{checkScalarNA}}} #' } #' #' Check vectors: #' \itemize{ #' \item{\code{\link{checkLogical}}} #' \item{\code{\link{checkNumeric}}} #' \item{\code{\link{checkInteger}}} #' \item{\code{\link{checkIntegerish}}} #' \item{\code{\link{checkCharacter}}} #' \item{\code{\link{checkComplex}}} #' \item{\code{\link{checkFactor}}} #' \item{\code{\link{checkList}}} #' \item{\code{\link{checkVector}}} #' \item{\code{\link{checkAtomic}}} #' \item{\code{\link{checkAtomicVector}}} #' } #' #' Check attributes: #' \itemize{ #' \item{\code{\link{checkClass}}} #' \item{\code{\link{checkNames}}} #' \item{\code{\link{checkNamed}}} (deprecated) #' } #' #' Check compound types: #' \itemize{ #' \item{\code{\link{checkArray}}} #' \item{\code{\link{checkDataFrame}}} #' \item{\code{\link{checkMatrix}}} #' } #' #' Check other built-in R types: #' \itemize{ #' \item{\code{\link{checkDate}}} #' \item{\code{\link{checkEnvironment}}} #' \item{\code{\link{checkFunction}}} #' \item{\code{\link{checkNull}}} #' } #' #' Check sets: #' \itemize{ #' \item{\code{\link{checkChoice}}} #' \item{\code{\link{checkSubset}}} #' \item{\code{\link{checkSetEqual}}} #' } #' #' File IO: #' \itemize{ #' \item{\code{\link{checkFileExists}}} #' \item{\code{\link{checkDirectoryExists}}} #' \item{\code{\link{checkPathForOutput}}} #' \item{\code{\link{checkAccess}}} #' } #' #' Popular data types in external packages: #' \itemize{ #' \item{\code{\link{checkBit}}} #' \item{\code{\link{checkDataTable}}} #' \item{\code{\link{checkR6}}} #' \item{\code{\link{checkTibble}}} #' } #' #' Safe coercion to integer: #' \itemize{ #' \item{\code{\link{asCount}}} #' \item{\code{\link{asInt}}} #' \item{\code{\link{asInteger}}} #' } #' #' Quick argument checks using a DSL: #' \itemize{ #' \item{\code{\link{qassert}}} #' \item{\code{\link{qassertr}}} #' } #' #' Misc: #' \itemize{ #' \item{\code{\link{checkOS}} (check operating system)} #' \item{\code{\link{assert}} (combine multiple checks into an assertion)} #' \item{\code{\link{anyMissing}}} #' \item{\code{\link{allMissing}}} #' \item{\code{\link{anyNaN}}} #' \item{\code{\link{wf}} (which.first and which.last)} #' } #' #' @importFrom utils head tail packageVersion getFromNamespace "_PACKAGE" checkmate = new.env(parent = emptyenv()) checkmate$os = c("windows", "mac", "linux", "solaris")[match(tolower(Sys.info()["sysname"]), c("windows", "darwin", "linux", "sunos"))] checkmate$listtypefuns = list2env(list( "logical" = is.logical, "integer" = is.integer, "integerish" = isIntegerish, "double" = is.double, "numeric" = is.numeric, "complex" = is.complex, "character" = is.character, "factor" = is.factor, "atomic" = is.atomic, "vector" = is.vector, "atomicvector" = function(x) !is.null(x) && is.atomic(x), "array" = is.array, "matrix" = is.matrix, "function" = is.function, "environment" = is.environment, "list" = is.list, "null" = is.null )) .onLoad = function(libpath, pkgname) { backports::import(pkgname, "dir.exists") } .onUnload = function (libpath) { library.dynam.unload("checkmate", libpath) # nocov } checkmate/R/anyMissing.R0000644000176200001440000000212712762010266014647 0ustar liggesusers#' Check if an object contains missing values #' #' @description #' Supported are atomic types (see \code{\link[base]{is.atomic}}), lists and data frames. #' Missingness is defined as \code{NA} or \code{NaN} for atomic types and data frame columns, #' \code{NULL} is defined as missing for lists.\cr #' \code{allMissing} applied to a \code{data.frame} returns \code{TRUE} if at least one column has #' only non-missing values. If you want to perform the less frequent check that there is not a single #' non-missing observation present in the \code{data.frame}, use \code{all(sapply(df, allMissing))} #' instead. #' #' @param x [\code{ANY}]\cr #' Object to check. #' @return [\code{logical(1)}] Returns \code{TRUE} if any (\code{anyMissing}) or all (\code{allMissing}) #' elements of \code{x} are missing (see details), \code{FALSE} otherwise. #' @useDynLib checkmate c_any_missing #' @export #' @examples #' anyMissing(c(1, 1)) #' anyMissing(c(1, NA)) #' anyMissing(list(1, NULL)) #' #' x = iris #' x[, "Species"] = NA #' anyMissing(x) #' allMissing(x) anyMissing = function(x) { .Call(c_any_missing, x) } checkmate/R/AssertCollection.R0000644000176200001440000000375313015020745016004 0ustar liggesusers#' Collect multiple assertions #' @name AssertCollection #' #' @param collection [\code{AssertCollection}]\cr #' Object of type \dQuote{AssertCollection} (constructed via \code{makeAssertCollection}). #' @description #' The function \code{makeAssertCollection()} returns a simple stack-like #' closure you can pass to all functions of the \code{assert*}-family. #' All messages get collected and can be reported with \code{reportAssertions()}. #' Alternatively, you can easily write your own report function or customize the the output of #' the report function to a certain degree. #' See the example on how to push custom messages or retrieve all stored messages. #' @return \code{makeAssertCollection()} returns an object of class \dQuote{AssertCollection} and #' \code{reportCollection} returns invisibly \code{TRUE} if no error is thrown (i.e., no message was #' collected). #' @examples #' x = "a" #' coll = makeAssertCollection() #' #' print(coll$isEmpty()) #' assertNumeric(x, add = coll) #' coll$isEmpty() #' coll$push("Custom error message") #' coll$getMessages() #' \dontrun{ #' reportAssertions(coll) #' } NULL #' @export #' @rdname AssertCollection makeAssertCollection = function() { msgs = character(0L) x = list(push = function(msg) msgs <<- c(msgs, msg), getMessages = function() msgs, isEmpty = function() length(msgs) == 0L) class(x) = "AssertCollection" x } #' @export print.AssertCollection = function(x, ...) { n = length(x$getMessages()) if (n == 0L) { cat("Empty collection\n") } else { cat(sprintf("Collection of %i assertion%s.\n", n, ifelse(n > 1L, "s", ""))) } } #' @export #' @rdname AssertCollection reportAssertions = function(collection) { assertClass(collection, "AssertCollection") if (!collection$isEmpty()) { msgs = collection$getMessages() context = "%i assertions failed:" err = c(sprintf(context, length(msgs)), strwrap(msgs, prefix = " * ")) stop(simpleError(paste0(err, collapse = "\n"), call = sys.call(1L))) } invisible(TRUE) } checkmate/R/anyInfinite.R0000644000176200001440000000100312762010266014773 0ustar liggesusers#' Check if an object contains infinite values #' #' @description #' Supported are atomic types (see \code{\link[base]{is.atomic}}), lists and data frames. #' #' @param x [\code{ANY}]\cr #' Object to check. #' @return [\code{logical(1)}] Returns \code{TRUE} if any element is \code{-Inf} or \code{Inf}. #' @useDynLib checkmate c_any_infinite #' @export #' @examples #' anyInfinite(1:10) #' anyInfinite(c(1:10, Inf)) #' iris[3, 3] = Inf #' anyInfinite(iris) anyInfinite = function(x) { .Call(c_any_infinite, x) } checkmate/vignettes/0000755000176200001440000000000013173633435014216 5ustar liggesuserscheckmate/vignettes/checkmate.Rmd0000644000176200001440000003005513162163362016604 0ustar liggesusers--- title: "Checkmate" author: "Michel Lang" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{checkmate} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r,include=FALSE} library(checkmate) ``` Ever used an R function that produced a not-very-helpful error message, just to discover after minutes of debugging that you simply passed a wrong argument? Blaming the laziness of the package author for not doing such standard checks (in a dynamically typed language such as R) is at least partially unfair, as R makes theses types of checks cumbersome and annoying. Well, that's how it was in the past. Enter checkmate. Virtually **every standard type of user error** when passing arguments into function can be caught with a simple, readable line which produces an **informative error message** in case. A substantial part of the package was written in C to **minimize any worries about execution time overhead**. ## Intro As a motivational example, consider you have a function to calculate the faculty of a natural number and the user may choose between using either the stirling approximation or R's `factorial` function (which internally uses the gamma function). Thus, you have two arguments, `n` and `method`. Argument `n` must obviously be a positive natural number and `method` must be either `"stirling"` or `"factorial"`. Here is a version of all the hoops you need to jump through to ensure that these simple requirements are met: ```{r} fact <- function(n, method = "stirling") { if (length(n) != 1) stop("Argument 'n' must have length 1") if (!is.numeric(n)) stop("Argument 'n' must be numeric") if (is.na(n)) stop("Argument 'n' may not be NA") if (is.double(n)) { if (is.nan(n)) stop("Argument 'n' may not be NaN") if (is.infinite(n)) stop("Argument 'n' must be finite") if (abs(n - round(n, 0)) > sqrt(.Machine$double.eps)) stop("Argument 'n' must be an integerish value") n <- as.integer(n) } if (n < 0) stop("Argument 'n' must be >= 0") if (length(method) != 1) stop("Argument 'method' must have length 1") if (!is.character(method) || !method %in% c("stirling", "factorial")) stop("Argument 'method' must be either 'stirling' or 'factorial'") if (method == "factorial") factorial(n) else sqrt(2 * pi * n) * (n / exp(1))^n } ``` And for comparison, here is the same function using checkmate: ```{r} fact <- function(n, method = "stirling") { assertCount(n) assertChoice(method, c("stirling", "factorial")) if (method == "factorial") factorial(n) else sqrt(2 * pi * n) * (n / exp(1))^n } ``` ## Function overview The functions can be split into four functional groups, indicated by their prefix. If prefixed with `assert`, an error is thrown if the corresponding check fails. Otherwise, the checked object is returned invisibly. There are many different coding styles out there in the wild, but most R programmers stick to either `camelBack` or `underscore_case`. Therefore, `checkmate` offers all functions in both flavors: `assert_count` is just an alias for `assertCount` but allows you to retain your favorite style. The family of functions prefixed with `test` always return the check result as logical value. Again, you can use `test_count` and `testCount` interchangeably. Functions starting with `check` return the error message as a string (or `TRUE` otherwise) and can be used if you need more control and, e.g., want to grep on the returned error message. `expect` is the last family of functions and is intended to be used with the [testthat package](https://cran.r-project.org/package=testthat). All performed checks are logged into the `testthat` reporter. Because `testthat` uses the `underscore_case`, the extension functions only come in the underscore style. All functions are categorized into objects to check on the [package help page](https://mllg.github.io/checkmate/reference/checkmate-package). ## In case you miss flexibility You can use [assert](https://mllg.github.io/checkmate/reference/assert) to perform multiple checks at once and throw an assertion if all checks fail. Here is an example where we check that x is either of class `foo` or class `bar`: ```{r} f <- function(x) { assert( checkClass(x, "foo"), checkClass(x, "bar") ) } ``` Note that `assert(, combine = "or")` and `assert(, combine = "and")` allow to control the logical combination of the specified checks, and that the former is the default. ## Argument Checks for the Lazy The following functions allow a special syntax to define argument checks using a special format specification. E.g., `qassert(x, "I+")` asserts that `x` is an integer vector with at least one element and no missing values. This very simple domain specific language covers a large variety of frequent argument checks with only a few keystrokes. You choose what you like best. * [qassert](https://mllg.github.io/checkmate/reference/qassert) * [qassertr](https://mllg.github.io/checkmate/reference/qassertr) ## checkmate as testthat extension To extend [testthat](https://cran.r-project.org/package=testthat), you need to IMPORT, DEPEND or SUGGEST on the `checkmate` package. Here is a minimal example: ```{r,eval=FALSE} # file: tests/test-all.R library(testthat) library(checkmate) # for testthat extensions test_check("mypkg") ``` Now you are all set and can use more than 30 new expectations in your tests. ```{r,eval=FALSE} test_that("checkmate is a sweet extension for testthat", { x = runif(100) expect_numeric(x, len = 100, any.missing = FALSE, lower = 0, upper = 1) # or, equivalent, using the lazy style: qexpect(x, "N100[0,1]") }) ``` ## Speed considerations In comparison with tediously writing the checks yourself in R (c.f. factorial example at the beginning of the vignette), R is sometimes a tad faster while performing checks on scalars. This seems odd at first, because checkmate is mostly written in C and should be comparably fast. Yet many of the functions in the `base` package are not regular functions, but primitives. While primitives jump directly into the C code, checkmate has to use the considerably slower `.Call` interface. As a result, it is possible to write (very simple) checks using only the base functions which, under some circumstances, slightly outperform checkmate. However, if you go one step further and wrap the custom check into a function to convenient re-use it, the performance gain is often lost (see benchmark 1). For larger objects the tide has turned because checkmate avoids many unnecessary intermediate variables. Also note that the quick/lazy implementation in `qassert`/`qtest`/`qexpect` is often a tad faster because only two arguments have to be evaluated (the object and the rule) to determine the set of checks to perform. Below you find some (probably unrepresentative) benchmark. But also note that this one here has been executed from inside `knitr` which is often the cause for outliers in the measured execution time. Better run the benchmark yourself to get unbiased results. ### Benchmark 1: Assert that `x` is a flag ```{r,dev="svg",fig.width=6,fig.height=4,dependson="init",eval=requireNamespace("microbenchmark", quietly = TRUE)} library(ggplot2) library(microbenchmark) x = TRUE r = function(x, na.ok = FALSE) { stopifnot(is.logical(x), length(x) == 1, na.ok || !is.na(x)) } cm = function(x) assertFlag(x) cmq = function(x) qassert(x, "B1") mb = microbenchmark(r(x), cm(x), cmq(x)) print(mb) autoplot(mb) ``` ### Benchmark 2: Assert that `x` is a numeric of length 1000 with no missing nor NaN values ```{r,dev="svg",fig.width=6,fig.height=4,eval=requireNamespace("microbenchmark", quietly = TRUE)} x = runif(1000) r = function(x) stopifnot(is.numeric(x) && length(x) == 1000 && all(!is.na(x) & x >= 0 & x <= 1)) cm = function(x) assertNumeric(x, len = 1000, any.missing = FALSE, lower = 0, upper = 1) cmq = function(x) qassert(x, "N1000[0,1]") mb = microbenchmark(r(x), cm(x), cmq(x)) print(mb) autoplot(mb) ``` ### Benchmark 3: Assert that `x` is a character vector with no missing values nor empty strings ```{r,dev="svg",fig.width=6,fig.height=4,eval=requireNamespace("microbenchmark", quietly = TRUE)} x = sample(letters, 10000, replace = TRUE) r = function(x) stopifnot(is.character(x) && !any(is.na(x)) && all(nchar(x) > 0)) cm = function(x) assertCharacter(x, any.missing = FALSE, min.chars = 1) cmq = function(x) qassert(x, "S+[1,]") mb = microbenchmark(r(x), cm(x), cmq(x)) print(mb) autoplot(mb) ``` ### Benchmark 4: Assert that `x` is a data frame with no missing values ```{r,dev="svg",fig.width=6,fig.height=4,eval=requireNamespace("microbenchmark", quietly = TRUE)} N = 10000 x = data.frame(a = runif(N), b = sample(letters[1:5], N, replace = TRUE), c = sample(c(FALSE, TRUE), N, replace = TRUE)) r = function(x) is.data.frame(x) && !any(sapply(x, function(x) any(is.na(x)))) cm = function(x) testDataFrame(x, any.missing = FALSE) cmq = function(x) qtest(x, "D") mb = microbenchmark(r(x), cm(x), cmq(x)) print(mb) autoplot(mb) # checkmate tries to stop as early as possible x$a[1] = NA mb = microbenchmark(r(x), cm(x), cmq(x)) print(mb) autoplot(mb) ``` ## Extending checkmate To extend checkmate a custom `check*` function has to be written. For example, to check for a square matrix one can re-use parts of checkmate and extend the check with additional functionality: ```{r} checkSquareMatrix = function(x, mode = NULL) { # check functions must return TRUE on success # and a custom error message otherwise res = checkMatrix(x, mode = mode) if (!isTRUE(res)) return(res) if (nrow(x) != ncol(x)) return("Must be square") return(TRUE) } # a quick test: X = matrix(1:9, nrow = 3) checkSquareMatrix(X) checkSquareMatrix(X, mode = "character") checkSquareMatrix(X[1:2, ]) ``` The respective counterparts to the `check`-function can be created using the constructors [makeAssertionFunction](https://mllg.github.io/checkmate/reference/makeAssertion), [makeTestFunction](https://mllg.github.io/checkmate/reference/makeTest) and [makeExpectationFunction](https://mllg.github.io/checkmate/reference/makeExpectation): ```{r} # For assertions: assert_square_matrix = assertSquareMatrix = makeAssertionFunction(checkSquareMatrix) print(assertSquareMatrix) # For tests: test_square_matrix = testSquareMatrix = makeTestFunction(checkSquareMatrix) print(testSquareMatrix) # For expectations: expect_square_matrix = makeExpectationFunction(checkSquareMatrix) print(expect_square_matrix) ``` Note that all the additional arguments `.var.name`, `add`, `info` and `label` are automatically joined with the function arguments of your custom check function. Also note that if you define these functions inside an R package, the constructors are called at build-time (thus, there is no negative impact on the runtime). ## Calling checkmate from C/C++ The package registers two functions which can be used in other packages' C/C++ code for argument checks. ```{c,eval=FALSE} SEXP qassert(SEXP x, const char *rule, const char *name); Rboolean qtest(SEXP x, const char *rule); ``` These are the counterparts to [qassert](https://mllg.github.io/checkmate/reference/qassert) and [qtest](https://mllg.github.io/checkmate/reference/qassert). Due to their simplistic interface, they perfectly suit the requirements of most type checks in C/C++. For detailed background information on the register mechanism, see the [Exporting C Code](http://r-pkgs.had.co.nz/src.html#clang) section in Hadley's Book "R Packages" or [WRE](https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Registering-native-routines). Here is a step-by-step guide to get you started: 1. Add `checkmate` to your "Imports" and "LinkingTo" sections in your DESCRIPTION file. 2. Create a stub C source file `"checkmate_stub.c"`. See example below. 3. Include the provided header file `` in each compilation unit where you want to use checkmate. ```{c,eval=FALSE} /* Example for (2), "checkmate_stub.c":*/ #include #include ``` ## Session Info For the sake of completeness, here the `sessionInfo()` for the benchmark (but remember the note before on `knitr` possibly biasing the results). ```{r} sessionInfo() ``` checkmate/README.md0000644000176200001440000000423313171614644013466 0ustar liggesusers# checkmate [![CRAN_Status_Badge](http://www.r-pkg.org/badges/version/checkmate)](https://cran.r-project.org/package=checkmate) [![Build Status](https://travis-ci.org/mllg/checkmate.svg?branch=master)](https://travis-ci.org/mllg/checkmate) [![Build status](https://ci.appveyor.com/api/projects/status/y4ayps61hjd3375o/branch/master?svg=true)](https://ci.appveyor.com/project/mllg/checkmate/branch/master) [![Coverage Status](https://img.shields.io/coveralls/mllg/checkmate.svg)](https://coveralls.io/r/mllg/checkmate?branch=master) [![Download Stats](http://cranlogs.r-pkg.org/badges/checkmate)](https://cran.r-project.org/package=checkmate) Fast and versatile argument checks for R. Ever used an R function that produced a not-very-helpful error message, just to discover after minutes of debugging that you simply passed a wrong argument? Blaming the laziness of the package author for not doing such standard checks (in a dynamically typed language such as R) is at least partially unfair, as R makes theses types of checks cumbersome and annoying. Well, that's how it was in the past. Enter checkmate. Virtually **every standard type of user error** when passing arguments into function can be caught with a simple, readable line which produces an **informative error message** in case. A substantial part of the package was written in C to **minimize any worries about execution time overhead**. Furthermore, the package provides over 30 expectations to extend the popular [testthat package](https://cran.r-project.org/package=testthat) for unit tests. ## Installation For the stable release, just install the latest version from [CRAN](https://cran.r-project.org/package=checkmate): ```{R} install.packages("checkmate") ``` For the development version, use [devtools](https://cran.r-project.org/package=devtools): ```{R} devtools::install_github("mllg/checkmate") ``` ## Resources * [R Journal Paper](https://journal.r-project.org/archive/2017/RJ-2017-028/index.html) * [NEWS](https://github.com/mllg/checkmate/blob/master/NEWS.md) * [Documentation/Vignettes](https://mllg.github.io/checkmate/) * [Grouped function reference](https://mllg.github.io/checkmate/reference/checkmate-package) checkmate/MD50000644000176200001440000002720413173640000012505 0ustar liggesusers92ffcedd3133548cc0f92c56157e8078 *DESCRIPTION b5327781a4c1f10d4f30a0cd22a4f00e *LICENSE b2d89252594b9657644f0adf3dd579bc *NAMESPACE 411afa339b47a952315055e9618ef4a9 *NEWS.md f0fc2aeb92b3d2014f6357308fd80954 *R/AssertCollection.R a7fc65b769f9477797c56c8c2af12339 *R/allMissing.R d4b005e269d2845ff89bed357a4e3d5f *R/anyInfinite.R 4e5ba9b259b46bf424e3ce1000f68e90 *R/anyMissing.R 65edb5b66b8a66217713a6aa2df5f3b9 *R/anyNaN.R 5790737b5442ebea7cbda675bcf845cd *R/asInteger.R 5ddf157b76c71ab46ca7848dc0dd8a9f *R/assert.R b41e73daedebeac4433df04594e1440e *R/checkAccess.R 7b56d45a334baf5ed3df5351e21f7beb *R/checkArray.R f16b4aea13b3cdba0d41b90422cc6331 *R/checkAtomic.R 94a969b14aec5b4f1d78e2e197cdabe7 *R/checkAtomicVector.R f569a74fd26266c20718939de8c9d9dc *R/checkBit.R ce1275b6366511e6543f8f0dac834f3c *R/checkCharacter.R 4f2ce2162c0524cba0615ea8ecc0f71d *R/checkChoice.R 882a70c4e09e1269ed6198fd22475a6e *R/checkClass.R 7e2a0da23501614b4a5234c7716c387a *R/checkComplex.R f183a66d07d9569ec5cb51e83a6858d9 *R/checkCount.R ee5ad9523512931c12c6fafa0af82511 *R/checkDataFrame.R 019d67d9e2f78bdc47f5989765fe8b1c *R/checkDataTable.R 4e44a2621bd08284111914a4085ef93c *R/checkDate.R d32c00660ef9c4b43866f454670736fe *R/checkDirectoryExists.R 213efc5bfb35e80f45f1d0a406c49e70 *R/checkEnvironment.R 58fd0bbe1ed6b11125e5e2013e92fe77 *R/checkFALSE.R 3ba719f42f004c171482d3f31da0d45c *R/checkFactor.R 96f53778f75a3e3309a3780479114a33 *R/checkFileExists.R 9e3dac4031f2b1a2538a3c6f8be8d1f7 *R/checkFlag.R 04691756e2f2209ad07a9f85787a3c46 *R/checkFunction.R c8259f61a372a95f8a72d8c9e56afd6e *R/checkInt.R 3f852ab97c30d3d2aae4c37fb0475cf6 *R/checkInteger.R 5a6eea91fc16c04191404498ad5afd42 *R/checkIntegerish.R 3a003fc041ab11d7e0015a069c1ccdc1 *R/checkList.R 4ad92ebbf2b6954dd49e2603c32d3a31 *R/checkLogical.R a77907ff924cf709c17dc5f9fec7a64b *R/checkMatrix.R 82ae9ed0bf0a6d025f8373e0da3b127d *R/checkNamed.R 92a47b072dc188cfc1a183158864c84c *R/checkNames.R 0b8ae1aa94964c09014463b1b684d381 *R/checkNull.R 304c2c610fe9f23a383e478b202158c6 *R/checkNumber.R 61473dc1085429b97022d4d0e8f4a7e6 *R/checkNumeric.R 489644560780caf623590aa036f74ef9 *R/checkOS.R 670447ea0e9e3e50bfb32fb54f574704 *R/checkPOSIXct.R 184245a6caa12048858447862188e707 *R/checkPathForOutput.R e896f407702d6cb8a9d4548b50eba7d8 *R/checkR6.R 6153863470172efebe1f720d99a55069 *R/checkScalar.R 45eb46b0426fec6bb9eed61609e45c7d *R/checkScalarNA.R bcaa4e971e6217d8a5f241e590a17974 *R/checkSetEqual.R 94bf1562cf0d489287575536c1880f39 *R/checkString.R 214255f1030ebc241e006acb1449d6f9 *R/checkSubset.R 1a4c95b4610a352631410c98e335ee77 *R/checkTRUE.R be1b008f8014412deaaa6043577428af *R/checkTibble.R 444955685dac38375d5843f1b603b83b *R/checkVector.R 80ae11a07596493bea7960e2eb65dd73 *R/coalesce.R 848ba0ecdbbe1daf517ec818c7445b69 *R/helper.R bd5ff342b970d92b9fa99f437af82b72 *R/isIntegerish.R 3b7156db275d6b5bcaeb3b92b5c284a9 *R/makeAssertion.R b64dfbf277899287a6ed1a67ba0655d0 *R/makeExpectation.R 81ed256883d6f8b55f9d1278c230997f *R/makeTest.R 2bcacedd9700a3595fc4292ebf573cca *R/matchArg.R bda6942a2f8c0cea23c06f5958aaffa8 *R/qassert.R 600a436fa2c69ef47f7a4a2ccc9a150d *R/qassertr.R 3f12a573026bdfe1a99ccd4678f2f4b1 *R/vname.R e461317d090f6344d1e56dc1cbfd4c20 *R/wfwl.R 43c4d87c049da6d543880a5c025a8d03 *R/zzz.R 39bf7482a077081f074b720c719186ca *README.md cb7ed5fc39dc4f9c4b6e5588caaa07d6 *build/vignette.rds 1fc7d9ccd9c68a9f21d76744c19fd6ed *inst/CITATION ada048880c36efe0c30ddb29f40dc95a *inst/doc/checkmate.R df44801f9cfbb477d6fa1a8928dd9a74 *inst/doc/checkmate.Rmd f3f36026a43d19cd644cc39f42130c82 *inst/doc/checkmate.html 022139fefe30297f3f1ef95ae27f3901 *inst/include/checkmate.h 7455ff6681ad01c81b9fe547128ec5d3 *inst/include/checkmate_stub.c 570556c5f559df4b9cbc2388e9138da9 *man/AssertCollection.Rd ed7f80b05a99aa497b5c64d92afd8024 *man/anyInfinite.Rd b52205c5c2f8b48e1b2e24d3154902d3 *man/anyMissing.Rd 5a8da757d242d5d2ff28254575a4adcf *man/anyNaN.Rd 031e652fbf9e95b54d95f6166dfff7e6 *man/asInteger.Rd 4a3d0c2113382a72083a812be3d2a9df *man/assert.Rd c89826dd6856ea159441637666be3a0b *man/checkAccess.Rd 7ff59bef61cbcb40540164049dbd3ca6 *man/checkArray.Rd a6d71ccf378a5361e7b2a916c525f36b *man/checkAtomic.Rd a74f19e1e4e7401d95dfe046abdc3ba7 *man/checkAtomicVector.Rd 90e1362e963a5ff165c06d29ca3ec939 *man/checkBit.Rd da496f490e33c8076daf68ada059ab33 *man/checkCharacter.Rd 3bf2bda541f28f2d76b060d5f78e4260 *man/checkChoice.Rd f07e431331fc8ec1865e14cb451522a2 *man/checkClass.Rd a990f4435c6a0df3a05b2fe345874eaa *man/checkComplex.Rd c958c20031a4565f50ee0c0af15eb4b8 *man/checkCount.Rd e0b5c732530949308e44c17cda847bb1 *man/checkDataFrame.Rd d185d83e029dec84fed2d29815394e77 *man/checkDataTable.Rd 6b1c12b2b9130a4e66159455d8a62828 *man/checkDate.Rd 5919bb79d6f38607aac0b03425aaeb10 *man/checkDirectoryExists.Rd 19de4c9199bb295d6c8e541382b45fea *man/checkEnvironment.Rd 99ecc1948754c7b940306be3ee274d2f *man/checkFALSE.Rd bd1fa1c55d46f941974c65760fd1b687 *man/checkFactor.Rd 6c0e648d725274a7fffe4de0f2e03283 *man/checkFileExists.Rd 5908d564dc09a96b9f2deffab63f74d0 *man/checkFlag.Rd e29c7dab0fe23856839173f38994e314 *man/checkFunction.Rd 49315124e5398b2872c9f868a8779d77 *man/checkInt.Rd 1cd021d7aee4d2e24bc097640caafe79 *man/checkInteger.Rd e213720cd3d87efcaa1026650b8b1aac *man/checkIntegerish.Rd de3071268b986e3b2c16f75e13ee87f4 *man/checkList.Rd c8d4c8f40169bfd137bc8825d2c56d6f *man/checkLogical.Rd 0586b10c35bcd9fcfad91a539604c2cb *man/checkMatrix.Rd 92aa14d3f8ae2d3af137e84dc3dec34a *man/checkNamed.Rd 6ce26ffeec459d928482594868cf7ae8 *man/checkNames.Rd 432abaf7326537bfd2e2869d8a79f5d4 *man/checkNull.Rd b2a1f0e1360d5558d7480a0ce2ccd457 *man/checkNumber.Rd cd4a031705db36a5d808362531f4bb0c *man/checkNumeric.Rd ff76d6bf66451a0b7f32457df46ccaa2 *man/checkOS.Rd 27625b74517354770578d82b6ba3098f *man/checkPOSIXct.Rd 71d1b03398a660599049282cf10403dd *man/checkPathForOutput.Rd dec677ef12c25841ad068205dddcf9ea *man/checkR6.Rd 6e1e7a21a25fd76db72bbb4ab2e1942a *man/checkScalar.Rd d70df85613744ea8d9d14377808de170 *man/checkScalarNA.Rd 7d9341e4e5700806002488a42b7a7ea0 *man/checkSetEqual.Rd e03293e45af3b1d815ed56dc3c7a5930 *man/checkString.Rd 51f3adbddce67a3a1d40f2540029f4df *man/checkSubset.Rd 44531cf5d2a63326c9e5f21e7a181c56 *man/checkTRUE.Rd 447bae69d0113a5d48c3ed1e6c080f17 *man/checkTibble.Rd ad95f422aba3703906540a3b9cc0f6b5 *man/checkVector.Rd bd0f0b96559364eed0f32356c63016b3 *man/checkmate-package.Rd df830e7a73a97a9dcce66037219a92ab *man/coalesce.Rd b721ce899c5dc3dccbba68300e3b1cfa *man/makeAssertion.Rd f376b428b69369ab6892702eb1b52220 *man/makeExpectation.Rd a2daf9577dda8990928cb09f6338ed99 *man/makeTest.Rd 5da6ef4e2155034d75d6c4f9e7825b9c *man/matchArg.Rd fd58a08360d5be0818c2ee8a75b500a2 *man/qassert.Rd f2171852fe8b8898bb1ed39d778ea210 *man/qassertr.Rd c7160018ecdaf8c566838d3f71bc9b76 *man/vname.Rd 5ca43dddbda998d18889073324aae733 *man/wf.Rd a5f5b2c236aeeb896de707ef532dcc55 *src/all_missing.c 101888b30f048a740255a0fcb070f2ac *src/all_missing.h 77958090f6b48da5b1edb5db306a2a3f *src/all_nchar.c 1a0bb91f81c7d32d2b004ef9b51053ee *src/all_nchar.h 6e856ebba2b0c07e8f1e6182e94663d3 *src/any_infinite.c f2a0f331684755210d28e3fc3c4bf50f *src/any_infinite.h a777df256c49111fa09da3b1323ff8de *src/any_missing.c 34d5f2fc42f1fdae8e5c72dd7ae07e57 *src/any_missing.h 316e8b4aa9c78d643ee248bff1630e4f *src/any_nan.c 3d45e097bbd0c4afdde69a240406a25f *src/any_nan.h 24c8f94121f4020a77681d01d68aa78c *src/checks.c 528671c090324c5f96deb14c5834d43f *src/checks.h 84757906f561f04275dc5ee86b1c6acd *src/guess_type.c c326cc3cce213308a04b56fa5abd179b *src/guess_type.h d7e1bd2bf7816a448b41607f405e87d1 *src/helper.c 81cb52d7727b6c15cd54b719d8e82201 *src/helper.h 65347bdf7c9bd3037987bbed5c06880b *src/init.c 00010fa6d87352c2cec0be9302eeccd7 *src/is_integerish.c 71f4e8ca3b541b864b3461285aa3aeb9 *src/is_integerish.h 5450ca1c505fbf7e15c94931e5fdb894 *src/qassert.c 5225e5f00e56469685bc49e7f6db7ad1 *src/qassert.h ac5712e9dd0895d94384230a4ff69af9 *src/which_first.c cb2491b8850ec35c63c2151e6a7b1475 *src/which_first.h 44694bd86ba5d694433561ccfac56fc5 *tests/test-all.R c1ff027a1cd43fe9b1dcd3c2264d216e *tests/testthat/helper.R c74b3874797c89c2ea1cfc9592ffab6e *tests/testthat/test_AssertCollection.R 88a300e6dcc491c577f62eb8d664dcd9 *tests/testthat/test_anyInfinite.R ba67b4d1d4a8943f802f1182e9dcfd42 *tests/testthat/test_anyMissing.R a4cdd9e64bb3ccbb6b6443142960b529 *tests/testthat/test_anyNaN.R 547027ffd3e1ab24d4cfe0c9bd72c260 *tests/testthat/test_asType.R ddaec2c7773e4d847cd1c41ce8747e07 *tests/testthat/test_assert.R 2305b8dd8b4a63730e4c81d8bba95f2b *tests/testthat/test_bit.R 7b1fc897c76160a3e179c3b24148b657 *tests/testthat/test_checkArray.R 52088640fa738f4ab7e657e8b9b4cd02 *tests/testthat/test_checkAtomic.R ad416dbe956f3e6eb38ff46f77a4d8b1 *tests/testthat/test_checkAtomicVector.R 1d8da96d20f327e9b34d3d0636a0d0cc *tests/testthat/test_checkCharacter.R 2e42d48f79042501412e48512d30d0fc *tests/testthat/test_checkChoice.R 7904b4f2ddf49611b508f7646b9aca83 *tests/testthat/test_checkClass.R 2501bf94e2f24021d01db9931f0f0e5d *tests/testthat/test_checkComplex.R 0bb3a368b5686c4917c154dacc7a3ceb *tests/testthat/test_checkCount.R af620ef74f50fb6ca5ebdfd5bc67cfb7 *tests/testthat/test_checkDataFrame.R 929e50a92732c5df427cd64bfd61386b *tests/testthat/test_checkDataTable.R 313830eabfe3dd1dee3fbf97de82dac6 *tests/testthat/test_checkDate.R 34c6dc60267982609546dfc50cdc58a5 *tests/testthat/test_checkEnvironment.R f7c6ce89bbbd44374eedaef0eef2b0ce *tests/testthat/test_checkFALSE.R d48dcd64af88c011a8b25197d3ac5bdf *tests/testthat/test_checkFactor.R fd29474a573a6dd6599fba67b75e500d *tests/testthat/test_checkFilesystem.R 2ca8bc06283a7c62bdd32f28ccdbda2a *tests/testthat/test_checkFlag.R a62888d365c865a34f1f2b5b5550702b *tests/testthat/test_checkFunction.R e4b3ab35eb4fe35849251783f8151fcd *tests/testthat/test_checkInt.R 7ba3825215a39e8925d1256deb3d5b87 *tests/testthat/test_checkInteger.R 0e1b8d0cab7a09b160e6011ae538dc9f *tests/testthat/test_checkIntegerish.R c79e76785947395d680243b0ab46ec83 *tests/testthat/test_checkList.R edd75ed2d26e8ab74c186bff3511a403 *tests/testthat/test_checkLogical.R e9ede6e2053898992d8792f29a54a591 *tests/testthat/test_checkMatrix.R 9a404b9aef86aa7901bee4ee0f03a807 *tests/testthat/test_checkNamed.R d0a0db3dbbe3b3592a9d06e247130904 *tests/testthat/test_checkNames.R 5ca56038ba855cffb5996db49724663b *tests/testthat/test_checkNull.R 522c310bf5964325aff7e7f94b89c8c8 *tests/testthat/test_checkNumber.R ce553e6e9807bcb3d3183cda5e77dc6e *tests/testthat/test_checkNumeric.R 69527e18449a95f746aac9c98efc2199 *tests/testthat/test_checkOS.R 5deadc9354cc2d67cb28dd486eb67b26 *tests/testthat/test_checkPOSIXct.R de75d8d474ee541b05666065f39378fd *tests/testthat/test_checkScalar.R 97f0622df0ea56467eecde699a8f5ba6 *tests/testthat/test_checkScalarNA.R 882b876a0249fec9e1b16b097d36e63a *tests/testthat/test_checkSetEqual.R 1bd8d79f850e7cd2d8a589f57cf720ec *tests/testthat/test_checkString.R 22c9f013f01f67d34a98c3ed80981816 *tests/testthat/test_checkSubset.R 2a4b87a44c90fb268588f6bf0b01beda *tests/testthat/test_checkTRUE.R 1fc52f3c370c106f17b898d974ecff3e *tests/testthat/test_checkTibble.R 7e3bd43a9d03e3e6156c5f0f3d94a6d6 *tests/testthat/test_checkVector.R 8753de609ab6604b57b1c752ccf6b7d0 *tests/testthat/test_deparse.R 44e25d51ee7e69b021bb6900a89d62ac *tests/testthat/test_guessType.R 37aad8ee749a597ee8c42028e1e061ca *tests/testthat/test_include.R 04a628f6abd687e087711af1ee88868d *tests/testthat/test_interoperability.R bd4632191649731cd59073f4005a4b2c *tests/testthat/test_makeFunction.R a43ada07c4347a5d2ba63dc04d49e5a0 *tests/testthat/test_matchArg.R 671d54f5bd04025e4a8f4248495c4d42 *tests/testthat/test_messages.R 00cbeec1a63a971705a89308f0e2d708 *tests/testthat/test_qassert.R ac5db60f84be6d837df71444b6b1d767 *tests/testthat/test_qassertr.R dbb2bdd89afb01adf92554eb6d9c61f1 *tests/testthat/test_r6.R 98d5ba13378e03edbc92debb3f37772e *tests/testthat/test_wf.R df44801f9cfbb477d6fa1a8928dd9a74 *vignettes/checkmate.Rmd checkmate/build/0000755000176200001440000000000013173633435013305 5ustar liggesuserscheckmate/build/vignette.rds0000644000176200001440000000030613173633435015643 0ustar liggesusersb```b`fab`b2 1# 'MHMM,I MAKI!ter# t0X A(eKM-FZ]?4-ީE0=(jؠjX2sRad9.nP&c0Gq?gQ~nݣ9JI,IK+Bcheckmate/DESCRIPTION0000644000176200001440000000432213173637777013732 0ustar liggesusersPackage: checkmate Type: Package Title: Fast and Versatile Argument Checks Description: Tests and assertions to perform frequent argument checks. A substantial part of the package was written in C to minimize any worries about execution time overhead. Version: 1.8.5 Authors@R: c( person("Michel", "Lang", NULL, "michellang@gmail.com", role = c("cre", "aut")), person("Bernd", "Bischl", NULL, "bernd_bischl@gmx.de", role = "ctb") ) URL: https://github.com/mllg/checkmate URLNote: https://github.com/mllg/checkmate BugReports: https://github.com/mllg/checkmate/issues NeedsCompilation: yes ByteCompile: yes Encoding: UTF-8 Depends: R (>= 3.0.0) Imports: backports (>= 1.1.0), utils Suggests: R6, bit, fastmatch, data.table (>= 1.9.8), devtools, ggplot2, knitr, magrittr, microbenchmark, rmarkdown, testthat (>= 0.11.0), tibble License: BSD_3_clause + file LICENSE VignetteBuilder: knitr RoxygenNote: 6.0.1 Collate: 'AssertCollection.R' 'allMissing.R' 'anyInfinite.R' 'anyMissing.R' 'anyNaN.R' 'asInteger.R' 'assert.R' 'helper.R' 'makeExpectation.R' 'makeTest.R' 'makeAssertion.R' 'checkAccess.R' 'checkArray.R' 'checkAtomic.R' 'checkAtomicVector.R' 'checkBit.R' 'checkCharacter.R' 'checkChoice.R' 'checkClass.R' 'checkComplex.R' 'checkCount.R' 'checkDataFrame.R' 'checkDataTable.R' 'checkDate.R' 'checkDirectoryExists.R' 'checkEnvironment.R' 'checkFALSE.R' 'checkFactor.R' 'checkFileExists.R' 'checkFlag.R' 'checkFunction.R' 'checkInt.R' 'checkInteger.R' 'checkIntegerish.R' 'checkList.R' 'checkLogical.R' 'checkMatrix.R' 'checkNamed.R' 'checkNames.R' 'checkNull.R' 'checkNumber.R' 'checkNumeric.R' 'checkOS.R' 'checkPOSIXct.R' 'checkPathForOutput.R' 'checkR6.R' 'checkScalar.R' 'checkScalarNA.R' 'checkSetEqual.R' 'checkString.R' 'checkSubset.R' 'checkTRUE.R' 'checkTibble.R' 'checkVector.R' 'coalesce.R' 'isIntegerish.R' 'matchArg.R' 'qassert.R' 'qassertr.R' 'vname.R' 'wfwl.R' 'zzz.R' Packaged: 2017-10-24 12:50:38 UTC; lang Author: Michel Lang [cre, aut], Bernd Bischl [ctb] Maintainer: Michel Lang Repository: CRAN Date/Publication: 2017-10-24 13:28:31 UTC checkmate/man/0000755000176200001440000000000013167637071012764 5ustar liggesuserscheckmate/man/checkIntegerish.Rd0000644000176200001440000001334613167637071016361 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkIntegerish.R \name{checkIntegerish} \alias{checkIntegerish} \alias{check_integerish} \alias{assertIntegerish} \alias{assert_integerish} \alias{testIntegerish} \alias{test_integerish} \alias{expect_integerish} \title{Check if an object is an integerish vector} \usage{ checkIntegerish(x, tol = sqrt(.Machine$double.eps), lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) check_integerish(x, tol = sqrt(.Machine$double.eps), lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) assertIntegerish(x, tol = sqrt(.Machine$double.eps), lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_integerish(x, tol = sqrt(.Machine$double.eps), lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testIntegerish(x, tol = sqrt(.Machine$double.eps), lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) test_integerish(x, tol = sqrt(.Machine$double.eps), lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) expect_integerish(x, tol = sqrt(.Machine$double.eps), lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{tol}{[\code{double(1)}]\cr Numerical tolerance used to check whether a double or complex can be converted. Default is \code{sqrt(.Machine$double.eps)}.} \item{lower}{[\code{numeric(1)}]\cr Lower value all elements of \code{x} must be greater than.} \item{upper}{[\code{numeric(1)}]\cr Upper value all elements of \code{x} must be lower than.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{sorted}{[\code{logical(1)}]\cr Elements must be sorted in ascending order. Missing values are ignored.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertIntegerish}/\code{assert_integerish} return \code{x} invisibly, whereas \code{checkIntegerish}/\code{check_integerish} and \code{testIntegerish}/\code{test_integerish} return \code{TRUE}. If the check is not successful, \code{assertIntegerish}/\code{assert_integerish} throws an error message, \code{testIntegerish}/\code{test_integerish} returns \code{FALSE}, and \code{checkIntegerish} returns a string with the error message. The function \code{expect_integerish} always returns an \code{\link[testthat]{expectation}}. } \description{ An integerish value is defined as value safely convertible to integer. This includes integers and numeric values which are close to an integer w.r.t. a numeric tolerance. } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \note{ To convert from integerish to integer, use \code{\link{asInteger}}. } \examples{ testIntegerish(1L) testIntegerish(1.) testIntegerish(1:2, lower = 1L, upper = 2L, any.missing = FALSE) } \seealso{ Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} } checkmate/man/vname.Rd0000644000176200001440000000073113047277570014363 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/vname.R \name{vname} \alias{vname} \title{Lookup a variable name} \usage{ vname(x) } \arguments{ \item{x}{[ANY]\cr Object.} } \value{ [\code{character(1)}] Variable name. } \description{ Tries to heuristically determine the variable name of \code{x} in the parent frame with a combination of \code{\link[base]{deparse}} and \code{\link[base]{substitute}}. Used for checkmate's error messages. } checkmate/man/checkBit.Rd0000644000176200001440000000575713160423672014776 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkBit.R \name{checkBit} \alias{checkBit} \alias{check_bit} \alias{assertBit} \alias{assert_bit} \alias{testBit} \alias{test_bit} \alias{expect_bit} \title{Check if an argument is a bit vector} \usage{ checkBit(x, len = NULL, min.len = NULL, max.len = NULL, min.0 = NULL, min.1 = NULL, null.ok = FALSE) check_bit(x, len = NULL, min.len = NULL, max.len = NULL, min.0 = NULL, min.1 = NULL, null.ok = FALSE) assertBit(x, len = NULL, min.len = NULL, max.len = NULL, min.0 = NULL, min.1 = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_bit(x, len = NULL, min.len = NULL, max.len = NULL, min.0 = NULL, min.1 = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testBit(x, len = NULL, min.len = NULL, max.len = NULL, min.0 = NULL, min.1 = NULL, null.ok = FALSE) test_bit(x, len = NULL, min.len = NULL, max.len = NULL, min.0 = NULL, min.1 = NULL, null.ok = FALSE) expect_bit(x, len = NULL, min.len = NULL, max.len = NULL, min.0 = NULL, min.1 = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{min.0}{[\code{integer(1)}]\cr Minimum number of elements being \dQuote{0}/\code{FALSE}/off.} \item{min.1}{[\code{integer(1)}]\cr Minimum number of elements being \dQuote{1}/\code{TRUE}/on.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertBit}/\code{assert_bit} return \code{x} invisibly, whereas \code{checkBit}/\code{check_bit} and \code{testBit}/\code{test_bit} return \code{TRUE}. If the check is not successful, \code{assertBit}/\code{assert_bit} throws an error message, \code{testBit}/\code{test_bit} returns \code{FALSE}, and \code{checkBit} returns a string with the error message. The function \code{expect_bit} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a bit vector } \examples{ library(bit) x = as.bit(replace(logical(10), sample(10, 5), TRUE)) testBit(x, len = 10, min.0 = 1) } checkmate/man/checkCharacter.Rd0000644000176200001440000001322413167637071016147 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkCharacter.R \name{checkCharacter} \alias{checkCharacter} \alias{check_character} \alias{assertCharacter} \alias{assert_character} \alias{testCharacter} \alias{test_character} \alias{expect_character} \title{Check if an argument is a vector of type character} \usage{ checkCharacter(x, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) check_character(x, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) assertCharacter(x, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_character(x, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testCharacter(x, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) test_character(x, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) expect_character(x, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{min.chars}{[\code{integer(1)}]\cr Minimum number of characters for each element of \code{x}.} \item{pattern}{[\code{character(1L)}]\cr Regular expression as used in \code{\link[base]{grepl}}. All non-missing elements of \code{x} must comply to this pattern.} \item{fixed}{[\code{character(1)}]\cr Substring to detect in \code{x}. Will be used as \code{pattern} in \code{\link[base]{grepl}} with option \code{fixed} set to \code{TRUE}. All non-missing elements of \code{x} must contain this substring.} \item{ignore.case}{[\code{logical(1)}]\cr See \code{\link[base]{grepl}}. Default is \code{FALSE}.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertCharacter}/\code{assert_character} return \code{x} invisibly, whereas \code{checkCharacter}/\code{check_character} and \code{testCharacter}/\code{test_character} return \code{TRUE}. If the check is not successful, \code{assertCharacter}/\code{assert_character} throws an error message, \code{testCharacter}/\code{test_character} returns \code{FALSE}, and \code{checkCharacter} returns a string with the error message. The function \code{expect_character} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a vector of type character } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testCharacter(letters, min.len = 1, any.missing = FALSE) testCharacter(letters, min.chars = 2) testCharacter("example", pattern = "xa") } \seealso{ Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} } checkmate/man/checkTRUE.Rd0000644000176200001440000000311213047277570015026 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkTRUE.R \name{checkTRUE} \alias{checkTRUE} \alias{check_true} \alias{assertTRUE} \alias{assert_true} \alias{testTRUE} \alias{test_true} \title{Check if an argument is TRUE} \usage{ checkTRUE(x, na.ok = FALSE) check_true(x, na.ok = FALSE) assertTRUE(x, na.ok = FALSE, .var.name = vname(x), add = NULL) assert_true(x, na.ok = FALSE, .var.name = vname(x), add = NULL) testTRUE(x, na.ok = FALSE) test_true(x, na.ok = FALSE) } \arguments{ \item{x}{[any]\cr Object to check.} \item{na.ok}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{FALSE}.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertTRUE.}/\code{assert_true.} return \code{x} invisibly, whereas \code{checkTRUE.}/\code{check_true.} and \code{testTRUE.}/\code{test_true.} return \code{TRUE}. If the check is not successful, \code{assertTRUE.}/\code{assert_true.} throws an error message, \code{testTRUE.}/\code{test_true.} returns \code{FALSE}, and \code{checkTRUE.} returns a string with the error message. The function \code{expect_true.} always returns an \code{\link[testthat]{expectation}}. } \description{ Simply checks if an argument is \code{TRUE}. } \examples{ testTRUE(TRUE) testTRUE(FALSE) } checkmate/man/checkNames.Rd0000644000176200001440000001041613154204557015311 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkNames.R \name{checkNames} \alias{checkNames} \alias{check_names} \alias{assertNames} \alias{assert_names} \alias{testNames} \alias{test_names} \alias{expect_names} \title{Check names to comply to specific rules} \usage{ checkNames(x, type = "named", subset.of = NULL, must.include = NULL, permutation.of = NULL, identical.to = NULL) check_names(x, type = "named", subset.of = NULL, must.include = NULL, permutation.of = NULL, identical.to = NULL) assertNames(x, type = "named", subset.of = NULL, must.include = NULL, permutation.of = NULL, identical.to = NULL, .var.name = vname(x), add = NULL) assert_names(x, type = "named", subset.of = NULL, must.include = NULL, permutation.of = NULL, identical.to = NULL, .var.name = vname(x), add = NULL) testNames(x, type = "named", subset.of = NULL, must.include = NULL, permutation.of = NULL, identical.to = NULL) test_names(x, type = "named", subset.of = NULL, must.include = NULL, permutation.of = NULL, identical.to = NULL) expect_names(x, type = "named", subset.of = NULL, must.include = NULL, permutation.of = NULL, identical.to = NULL, info = NULL, label = vname(x)) } \arguments{ \item{x}{[\code{character} || \code{NULL}]\cr Names to check using rules defined via \code{type}.} \item{type}{[character(1)]\cr Type of formal check(s) to perform on the names. \describe{ \item{unnamed:}{Checks \code{x} to be \code{NULL}.} \item{named:}{Checks \code{x} for regular names which excludes names to be \code{NA} or empty (\code{""}).} \item{unique:}{Performs checks like with \dQuote{named} and additionally tests for non-duplicated names.} \item{strict:}{Performs checks like with \dQuote{unique} and additionally fails for names with UTF-8 characters and names which do not comply to R's variable name restrictions. As regular expression, this is \dQuote{^[.]*[a-zA-Z]+[a-zA-Z0-9._]*$}.} } Note that for zero-length \code{x}, all these name checks evaluate to \code{TRUE}.} \item{subset.of}{[\code{character}]\cr Names provided in \code{x} must be subset of the set \code{subset.of}.} \item{must.include}{[\code{character}]\cr Names provided in \code{x} must be a superset of the set \code{must.include}.} \item{permutation.of}{[\code{character}]\cr Names provided in \code{x} must be a permutation of the set \code{permutation.of}. Duplicated names in \code{permutation.of} are stripped out and duplicated names in \code{x} thus lead to a failed check. Use this argument instead of \code{identical.to} if the order of the names is not relevant.} \item{identical.to}{[\code{character}]\cr Names provided in \code{x} must be identical to the vector \code{identical.to}. Use this argument instead of \code{permutation.of} if the order of the names is relevant.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertNamed}/\code{assert_named} return \code{x} invisibly, whereas \code{checkNamed}/\code{check_named} and \code{testNamed}/\code{test_named} return \code{TRUE}. If the check is not successful, \code{assertNamed}/\code{assert_named} throws an error message, \code{testNamed}/\code{test_named} returns \code{FALSE}, and \code{checkNamed} returns a string with the error message. The function \code{expect_named} always returns an \code{\link[testthat]{expectation}}. } \description{ Similar to \code{\link{checkNamed}} but you can pass the names directly. } \examples{ x = 1:3 testNames(x, "unnamed") names(x) = letters[1:3] testNames(x, "unique") cn = c("Species", "Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width") assertNames(names(iris), permutation.of = cn) } \seealso{ Other attributes: \code{\link{checkClass}}, \code{\link{checkNamed}} } checkmate/man/qassert.Rd0000644000176200001440000001104213047277570014734 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/qassert.R \name{qassert} \alias{qassert} \alias{qtest} \alias{qexpect} \title{Quick argument checks on (builtin) R types} \usage{ qassert(x, rules, .var.name = vname(x)) qtest(x, rules) qexpect(x, rules, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object the check.} \item{rules}{[\code{character}]\cr Set of rules. See details.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in error messages. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ \code{qassert} throws an \code{R} exception if object \code{x} does not comply to at least one of the \code{rules} and returns the tested object invisibly otherwise. \code{qtest} behaves the same way but returns \code{FALSE} if none of the \code{rules} comply. \code{qexpect} is intended to be inside the unit test framework \code{\link[testthat]{testthat}} and returns an \code{\link[testthat]{expectation}}. } \description{ The provided functions parse rules which allow to express some of the most frequent argument checks by typing just a few letters. } \details{ The rule is specified in up to three parts. \enumerate{ \item{ Class and missingness check. The first letter is an abbreviation for the class. If it is provided uppercase, missing values are prohibited. Supported abbreviations: \tabular{rl}{ \code{[bB]} \tab Bool / logical.\cr \code{[iI]} \tab Integer.\cr \code{[xX]} \tab Integerish (numeric convertible to integer, see \code{\link{checkIntegerish}}).\cr \code{[rR]} \tab Real / double.\cr \code{[cC]} \tab Complex.\cr \code{[nN]} \tab Numeric (integer or double).\cr \code{[sS]} \tab String / character.\cr \code{[fF]} \tab Factor\cr \code{[aA]} \tab Atomic.\cr \code{[vV]} \tab Atomic vector (see \code{\link{checkAtomicVector}}).\cr \code{[lL]} \tab List. Missingness is defined as \code{NULL} element.\cr \code{[mM]} \tab Matrix.\cr \code{[dD]} \tab Data.frame. Missingness is checked recursively on columns.\cr \code{[e]} \tab Environment.\cr \code{[0]} \tab \code{NULL}.\cr \code{[*]} \tab placeholder to allow any type. } Note that the check for missingness does not distinguish between \code{NaN} and \code{NA}. Infinite values are not treated as missing, but can be caught using boundary checks (part 3). } \item{ Length definition. This can be one of \tabular{rl}{ \code{[*]} \tab any length,\cr \code{[?]} \tab length of zero or one,\cr \code{[+]} \tab length of at least one, or\cr \code{[0-9]+} \tab exact length specified as integer. } Preceding the exact length with one of the comparison operators \code{=}/\code{==}, \code{<}, \code{<=}, \code{>=} or \code{>} is also supported. } \item{ Range check as two numbers separated by a comma, enclosed by square brackets (endpoint included) or parentheses (endpoint excluded). For example, \dQuote{[0, 3)} results in \code{all(x >= 0 & x < 3)}. The lower and upper bound may be omitted which is the equivalent of a negative or positive infinite bound, respectively. By definition \code{[0,]} contains \code{Inf}, while \code{[0,)} does not. The same holds for the left (lower) boundary and \code{-Inf}. E.g., the rule \dQuote{N1()} checks for a single finite numeric which is not NA, while \dQuote{N1[)} allows \code{-Inf}. } } } \note{ The functions are inspired by the blog post of Bogumił Kamiński: \url{http://rsnippets.blogspot.de/2013/06/testing-function-agruments-in-gnu-r.html}. The implementation is mostly written in C to minimize the overhead. } \examples{ # logical of length 1 qtest(NA, "b1") # logical of length 1, NA not allowed qtest(NA, "B1") # logical of length 0 or 1, NA not allowed qtest(TRUE, "B?") # numeric with length > 0 qtest(runif(10), "n+") # integer with length > 0, NAs not allowed, all integers >= 0 and < Inf qtest(1:3, "I+[0,)") # either an emtpy list or a character vector with <=5 elements qtest(1, c("l0", "s<=5")) # data frame with at least one column and no missing value in any column qtest(iris, "D+") } \seealso{ \code{\link{qtestr}} and \code{\link{qassertr}} for efficient checks of list elements and data frame columns. } checkmate/man/checkPathForOutput.Rd0000644000176200001440000000540113117521632017023 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkPathForOutput.R \name{checkPathForOutput} \alias{checkPathForOutput} \alias{check_path_for_output} \alias{assertPathForOutput} \alias{assert_path_for_output} \alias{testPathForOutput} \alias{test_path_for_output} \alias{expect_path_for_output} \title{Check if a path is suited for creating an output file} \usage{ checkPathForOutput(x, overwrite = FALSE) check_path_for_output(x, overwrite = FALSE) assertPathForOutput(x, overwrite = FALSE, .var.name = vname(x), add = NULL) assert_path_for_output(x, overwrite = FALSE, .var.name = vname(x), add = NULL) testPathForOutput(x, overwrite = FALSE) test_path_for_output(x, overwrite = FALSE) expect_path_for_output(x, overwrite = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{overwrite}{[\code{logical(1)}]\cr If \code{TRUE}, an existing file in place is allowed if it it is both readable and writable. Default is \code{FALSE}.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertPathForOutput}/\code{assert_path_for_output} return \code{x} invisibly, whereas \code{checkPathForOutput}/\code{check_path_for_output} and \code{testPathForOutput}/\code{test_path_for_output} return \code{TRUE}. If the check is not successful, \code{assertPathForOutput}/\code{assert_path_for_output} throws an error message, \code{testPathForOutput}/\code{test_path_for_output} returns \code{FALSE}, and \code{checkPathForOutput} returns a string with the error message. The function \code{expect_path_for_output} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if a file path can be safely be used to create a file and write to it. This is checked: \itemize{ \item{Does \code{dirname(x)} exist?} \item{Does no file under path \code{x} exist?} \item{Is \code{dirname(x)} writable?} } Paths are relative to the current working directory. } \examples{ # Can we create a file in the tempdir? testPathForOutput(file.path(tempdir(), "process.log")) } \seealso{ Other filesystem: \code{\link{checkAccess}}, \code{\link{checkDirectoryExists}}, \code{\link{checkFileExists}} } checkmate/man/checkPOSIXct.Rd0000644000176200001440000001116013167637071015501 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkPOSIXct.R \name{checkPOSIXct} \alias{checkPOSIXct} \alias{check_posixct} \alias{assertPOSIXct} \alias{assert_posixct} \alias{testPOSIXct} \alias{test_posixct} \alias{expect_posixct} \title{Check that an argument is a date/time object in POSIXct format} \usage{ checkPOSIXct(x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, null.ok = FALSE) check_posixct(x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, null.ok = FALSE) assertPOSIXct(x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_posixct(x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL) testPOSIXct(x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, null.ok = FALSE) test_posixct(x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, null.ok = FALSE) expect_posixct(x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{lower}{[\code{\link[base]{Date}}]\cr All non-missing dates in \code{x} must be >= this POSIXct time. Must be provided in the same timezone as \code{x}.} \item{upper}{[\code{\link[base]{Date}}]\cr All non-missing dates in \code{x} must be <= this POSIXct time. Must be provided in the same timezone as \code{x}.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{sorted}{[\code{logical(1)}]\cr Elements must be sorted in ascending order. Missing values are ignored.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertAtomic}/\code{assert_atomic} return \code{x} invisibly, whereas \code{checkAtomic}/\code{check_atomic} and \code{testAtomic}/\code{test_atomic} return \code{TRUE}. If the check is not successful, \code{assertAtomic}/\code{assert_atomic} throws an error message, \code{testAtomic}/\code{test_atomic} returns \code{FALSE}, and \code{checkAtomic} returns a string with the error message. The function \code{expect_atomic} always returns an \code{\link[testthat]{expectation}}. } \description{ Checks that an object is of class \code{\link[base]{POSIXct}}. } \seealso{ Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkVector}} } checkmate/man/makeAssertion.Rd0000644000176200001440000000474213047277570016070 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/makeAssertion.R \name{makeAssertion} \alias{makeAssertion} \alias{makeAssertionFunction} \title{Turn a Check into an Assertion} \usage{ makeAssertion(x, res, var.name, collection) makeAssertionFunction(check.fun, c.fun = NULL, env = parent.frame()) } \arguments{ \item{x}{[any]\cr Object to check.} \item{res}{[\code{TRUE} | \code{character(1)}]\cr The result of a check function: \code{TRUE} for successful checks, and an error message as string otherwise.} \item{var.name}{[\code{character(1)}]\cr The custom name for \code{x} as passed to any \code{assert*} function. Defaults to a heuristic name lookup.} \item{collection}{[\code{\link{AssertCollection}}]\cr If an \code{\link{AssertCollection}} is provided, the error message is stored in it. If \code{NULL}, an exception is raised if \code{res} is not \code{TRUE}.} \item{check.fun}{[\code{function}]\cr Function which checks the input. Must return \code{TRUE} on success and a string with the error message otherwise.} \item{c.fun}{[\code{character(1)}]\cr If not \code{NULL}, instead of calling the function \code{check.fun}, use \code{.Call} to call a C function \dQuote{c.fun} with the identical set of parameters. The C function must be registered as a native symbol, see \code{\link[base]{.Call}}. Useful if \code{check.fun} is just a simple wrapper.} \item{env}{[\code{environment}]\cr The environment of the created function. Default is the \code{\link[base]{parent.frame}}.} } \value{ \code{makeAssertion} invisibly returns the checked object if the check was successful, and an exception is raised (or its message stored in the collection) otherwise. \code{makeAssertionFunction} returns a \code{function}. } \description{ \code{makeAssertion} is the internal function used to evaluate the result of a check and throw an exception if necessary. \code{makeAssertionFunction} can be used to automatically create an assertion function based on a check function (see example). } \examples{ # Simple custom check function checkFalse = function(x) if (!identical(x, FALSE)) "Must be FALSE" else TRUE # Create the respective assert function assertFalse = function(x, .var.name = vname(x), add = NULL) { res = checkFalse(x) makeAssertion(x, res, .var.name, add) } # Alternative: Automatically create such a function assertFalse = makeAssertionFunction(checkFalse) print(assertFalse) } \seealso{ Other CustomConstructors: \code{\link{makeExpectation}}, \code{\link{makeTest}} } checkmate/man/checkArray.Rd0000644000176200001440000001004513167637071015327 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkArray.R \name{checkArray} \alias{checkArray} \alias{check_array} \alias{assertArray} \alias{assert_array} \alias{testArray} \alias{test_array} \alias{expect_array} \title{Check if an argument is an array} \usage{ checkArray(x, mode = NULL, any.missing = TRUE, d = NULL, min.d = NULL, max.d = NULL, null.ok = FALSE) check_array(x, mode = NULL, any.missing = TRUE, d = NULL, min.d = NULL, max.d = NULL, null.ok = FALSE) assertArray(x, mode = NULL, any.missing = TRUE, d = NULL, min.d = NULL, max.d = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_array(x, mode = NULL, any.missing = TRUE, d = NULL, min.d = NULL, max.d = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testArray(x, mode = NULL, any.missing = TRUE, d = NULL, min.d = NULL, max.d = NULL, null.ok = FALSE) test_array(x, mode = NULL, any.missing = TRUE, d = NULL, min.d = NULL, max.d = NULL, null.ok = FALSE) expect_array(x, mode = NULL, any.missing = TRUE, d = NULL, min.d = NULL, max.d = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{mode}{[\code{character(1)}]\cr Storage mode of the array. Arrays can hold vectors, i.e. \dQuote{logical}, \dQuote{integer}, \dQuote{integerish}, \dQuote{double}, \dQuote{numeric}, \dQuote{complex}, \dQuote{character} and \dQuote{list}. You can also specify \dQuote{atomic} here to explicitly prohibit lists. Default is \code{NULL} (no check).} \item{any.missing}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{TRUE}.} \item{d}{[\code{integer(1)}]\cr Exact number of dimensions of array \code{x}. Default is \code{NULL} (no check).} \item{min.d}{[\code{integer(1)}]\cr Minimum number of dimensions of array \code{x}. Default is \code{NULL} (no check).} \item{max.d}{[\code{integer(1)}]\cr Maximum number of dimensions of array \code{x}. Default is \code{NULL} (no check).} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertArray}/\code{assert_array} return \code{x} invisibly, whereas \code{checkArray}/\code{check_array} and \code{testArray}/\code{test_array} return \code{TRUE}. If the check is not successful, \code{assertArray}/\code{assert_array} throws an error message, \code{testArray}/\code{test_array} returns \code{FALSE}, and \code{checkArray} returns a string with the error message. The function \code{expect_array} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is an array } \examples{ checkArray(array(1:27, dim = c(3, 3, 3)), d = 3) } \seealso{ Other basetypes: \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} Other compound: \code{\link{checkDataFrame}}, \code{\link{checkDataTable}}, \code{\link{checkMatrix}}, \code{\link{checkTibble}} } checkmate/man/anyMissing.Rd0000644000176200001440000000252013047277570015374 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/allMissing.R, R/anyMissing.R \name{allMissing} \alias{allMissing} \alias{anyMissing} \title{Check if an object contains missing values} \usage{ allMissing(x) anyMissing(x) } \arguments{ \item{x}{[\code{ANY}]\cr Object to check.} } \value{ [\code{logical(1)}] Returns \code{TRUE} if any (\code{anyMissing}) or all (\code{allMissing}) elements of \code{x} are missing (see details), \code{FALSE} otherwise. } \description{ Supported are atomic types (see \code{\link[base]{is.atomic}}), lists and data frames. Missingness is defined as \code{NA} or \code{NaN} for atomic types and data frame columns, \code{NULL} is defined as missing for lists.\cr \code{allMissing} applied to a \code{data.frame} returns \code{TRUE} if at least one column has only non-missing values. If you want to perform the less frequent check that there is not a single non-missing observation present in the \code{data.frame}, use \code{all(sapply(df, allMissing))} instead. } \examples{ allMissing(1:2) allMissing(c(1, NA)) allMissing(c(NA, NA)) x = data.frame(a = 1:2, b = NA) # Note how allMissing combines the results for data frames: allMissing(x) all(sapply(x, allMissing)) anyMissing(c(1, 1)) anyMissing(c(1, NA)) anyMissing(list(1, NULL)) x = iris x[, "Species"] = NA anyMissing(x) allMissing(x) } checkmate/man/checkString.Rd0000644000176200001440000000735513105020556015513 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkString.R \name{checkString} \alias{checkString} \alias{check_string} \alias{assertString} \alias{assert_string} \alias{testString} \alias{test_string} \alias{expect_string} \title{Check if an argument is a string} \usage{ checkString(x, na.ok = FALSE, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE) check_string(x, na.ok = FALSE, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE) assertString(x, na.ok = FALSE, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_string(x, na.ok = FALSE, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL) testString(x, na.ok = FALSE, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE) test_string(x, na.ok = FALSE, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE) expect_string(x, na.ok = FALSE, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{na.ok}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{FALSE}.} \item{min.chars}{[\code{integer(1)}]\cr Minimum number of characters for each element of \code{x}.} \item{pattern}{[\code{character(1L)}]\cr Regular expression as used in \code{\link[base]{grepl}}. All non-missing elements of \code{x} must comply to this pattern.} \item{fixed}{[\code{character(1)}]\cr Substring to detect in \code{x}. Will be used as \code{pattern} in \code{\link[base]{grepl}} with option \code{fixed} set to \code{TRUE}. All non-missing elements of \code{x} must contain this substring.} \item{ignore.case}{[\code{logical(1)}]\cr See \code{\link[base]{grepl}}. Default is \code{FALSE}.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertString}/\code{assert_string} return \code{x} invisibly, whereas \code{checkString}/\code{check_string} and \code{testString}/\code{test_string} return \code{TRUE}. If the check is not successful, \code{assertString}/\code{assert_string} throws an error message, \code{testString}/\code{test_string} returns \code{FALSE}, and \code{checkString} returns a string with the error message. The function \code{expect_string} always returns an \code{\link[testthat]{expectation}}. } \description{ A string is defined as a scalar character vector. } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testString("a") testString(letters) } \seealso{ Other scalars: \code{\link{checkCount}}, \code{\link{checkFlag}}, \code{\link{checkInt}}, \code{\link{checkNumber}}, \code{\link{checkScalarNA}}, \code{\link{checkScalar}} } checkmate/man/assert.Rd0000644000176200001440000000250713047277570014561 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/assert.R \name{assert} \alias{assert} \title{Combine multiple checks into one assertion} \usage{ assert(..., combine = "or", .var.name = NULL) } \arguments{ \item{...}{[any]\cr List of calls to check functions.} \item{combine}{[\code{character(1)}]\cr \dQuote{or} or \dQuote{and} to combine the check functions with an OR or AND, respectively.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in error messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Throws an error if all checks fail and invisibly returns \code{TRUE} otherwise. } \description{ You can call this function with an arbitrary number of of \code{check*} functions, i.e. functions provided by this package or your own functions which return \code{TRUE} on success and the error message as \code{character(1)} otherwise. The resulting assertion is successful, if \code{combine} is \dQuote{or} (default) and at least one check evaluates to \code{TRUE} or \code{combine} is \dQuote{and} and all checks evaluate to \code{TRUE}. Otherwise, \code{assert} throws an informative error message. } \examples{ x = 1:10 assert(checkNull(x), checkInteger(x, any.missing = FALSE)) \dontrun{ x = 1 assert(checkChoice(x, c("a", "b")), checkDataFrame(x)) } } checkmate/man/checkAtomic.Rd0000644000176200001440000001004313167637071015463 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkAtomic.R \name{checkAtomic} \alias{checkAtomic} \alias{check_atomic} \alias{assertAtomic} \alias{assert_atomic} \alias{testAtomic} \alias{test_atomic} \alias{expect_atomic} \title{Check that an argument is an atomic vector} \usage{ checkAtomic(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL) check_atomic(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL) assertAtomic(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, .var.name = vname(x), add = NULL) assert_atomic(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, .var.name = vname(x), add = NULL) testAtomic(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL) test_atomic(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL) expect_atomic(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertAtomic}/\code{assert_atomic} return \code{x} invisibly, whereas \code{checkAtomic}/\code{check_atomic} and \code{testAtomic}/\code{test_atomic} return \code{TRUE}. If the check is not successful, \code{assertAtomic}/\code{assert_atomic} throws an error message, \code{testAtomic}/\code{test_atomic} returns \code{FALSE}, and \code{checkAtomic} returns a string with the error message. The function \code{expect_atomic} always returns an \code{\link[testthat]{expectation}}. } \description{ For the definition of \dQuote{atomic}, see \code{\link[base]{is.atomic}}. } \examples{ testAtomic(letters, min.len = 1L, any.missing = FALSE) } \seealso{ Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} Other atomicvector: \code{\link{checkAtomicVector}}, \code{\link{checkVector}} } checkmate/man/checkChoice.Rd0000644000176200001440000000610513167073256015444 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkChoice.R \name{checkChoice} \alias{checkChoice} \alias{check_choice} \alias{assertChoice} \alias{assert_choice} \alias{testChoice} \alias{test_choice} \alias{expect_choice} \title{Check if an object is an element of a given set} \usage{ checkChoice(x, choices, null.ok = FALSE, fmatch = FALSE) check_choice(x, choices, null.ok = FALSE, fmatch = FALSE) assertChoice(x, choices, null.ok = FALSE, fmatch = FALSE, .var.name = vname(x), add = NULL) assert_choice(x, choices, null.ok = FALSE, fmatch = FALSE, .var.name = vname(x), add = NULL) testChoice(x, choices, null.ok = FALSE, fmatch = FALSE) test_choice(x, choices, null.ok = FALSE, fmatch = FALSE) expect_choice(x, choices, null.ok = FALSE, fmatch = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{choices}{[\code{atomic}]\cr Set of possible values.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{fmatch}{[\code{logical(1)}]\cr Use the set operations implemented in \code{\link[fastmatch]{fmatch}} in package \pkg{fastmatch}. If \pkg{fastmatch} is not installed, this silently falls back to \code{\link[base]{match}}. \code{\link[fastmatch]{fmatch}} modifies \code{y} by reference: A hash table is added as attribute which is used in subsequent calls.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertChoice}/\code{assert_choice} return \code{x} invisibly, whereas \code{checkChoice}/\code{check_choice} and \code{testChoice}/\code{test_choice} return \code{TRUE}. If the check is not successful, \code{assertChoice}/\code{assert_choice} throws an error message, \code{testChoice}/\code{test_choice} returns \code{FALSE}, and \code{checkChoice} returns a string with the error message. The function \code{expect_choice} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an object is an element of a given set } \note{ The object \code{x} must be of the same type as the set w.r.t. \code{\link[base]{typeof}}. Integers and doubles are both treated as numeric. } \examples{ testChoice("x", letters) # x is not converted before the comparison (except for numerics) testChoice(factor("a"), "a") testChoice(1, "1") testChoice(1, as.integer(1)) } \seealso{ Other set: \code{\link{checkSetEqual}}, \code{\link{checkSubset}} } checkmate/man/checkDate.Rd0000644000176200001440000001047013167637071015130 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkDate.R \name{checkDate} \alias{checkDate} \alias{check_date} \alias{assertDate} \alias{assert_date} \alias{testDate} \alias{test_date} \alias{expect_date} \title{Check that an argument is a Date} \usage{ checkDate(x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, null.ok = FALSE) check_date(x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, null.ok = FALSE) assertDate(x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_date(x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL) testDate(x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, null.ok = FALSE) test_date(x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, null.ok = FALSE) expect_date(x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{lower}{[\code{\link[base]{Date}}]\cr All non-missing dates in \code{x} must be >= this date. Comparison is done via \code{\link[base]{Ops.Date}}.} \item{upper}{[\code{\link[base]{Date}}]\cr All non-missing dates in \code{x} must be before <= this date. Comparison is done via \code{\link[base]{Ops.Date}}.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertAtomic}/\code{assert_atomic} return \code{x} invisibly, whereas \code{checkAtomic}/\code{check_atomic} and \code{testAtomic}/\code{test_atomic} return \code{TRUE}. If the check is not successful, \code{assertAtomic}/\code{assert_atomic} throws an error message, \code{testAtomic}/\code{test_atomic} returns \code{FALSE}, and \code{checkAtomic} returns a string with the error message. The function \code{expect_atomic} always returns an \code{\link[testthat]{expectation}}. } \description{ Checks that an object is of class \code{\link[base]{Date}}. } \seealso{ Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} } checkmate/man/checkNumeric.Rd0000644000176200001440000001236013167637071015655 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkNumeric.R \name{checkNumeric} \alias{checkNumeric} \alias{check_numeric} \alias{assertNumeric} \alias{assert_numeric} \alias{testNumeric} \alias{test_numeric} \alias{expect_numeric} \title{Check that an argument is a vector of type numeric} \usage{ checkNumeric(x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) check_numeric(x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) assertNumeric(x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_numeric(x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testNumeric(x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) test_numeric(x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) expect_numeric(x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{lower}{[\code{numeric(1)}]\cr Lower value all elements of \code{x} must be greater than.} \item{upper}{[\code{numeric(1)}]\cr Upper value all elements of \code{x} must be lower than.} \item{finite}{[\code{logical(1)}]\cr Check for only finite values? Default is \code{FALSE}.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{sorted}{[\code{logical(1)}]\cr Elements must be sorted in ascending order. Missing values are ignored.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertNumeric}/\code{assert_numeric} return \code{x} invisibly, whereas \code{checkNumeric}/\code{check_numeric} and \code{testNumeric}/\code{test_numeric} return \code{TRUE}. If the check is not successful, \code{assertNumeric}/\code{assert_numeric} throws an error message, \code{testNumeric}/\code{test_numeric} returns \code{FALSE}, and \code{checkNumeric} returns a string with the error message. The function \code{expect_numeric} always returns an \code{\link[testthat]{expectation}}. } \description{ Check that an argument is a vector of type numeric } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testNumeric(1) testNumeric(1, min.len = 1, lower = 0) } \seealso{ Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} } checkmate/man/anyNaN.Rd0000644000176200001440000000076413047277570014447 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/anyNaN.R \name{anyNaN} \alias{anyNaN} \title{Check if an object contains NaN values} \usage{ anyNaN(x) } \arguments{ \item{x}{[\code{ANY}]\cr Object to check.} } \value{ [\code{logical(1)}] Returns \code{TRUE} if any element is \code{NaN}. } \description{ Supported are atomic types (see \code{\link[base]{is.atomic}}), lists and data frames. } \examples{ anyNaN(1:10) anyNaN(c(1:10, NaN)) iris[3, 3] = NaN anyNaN(iris) } checkmate/man/checkNull.Rd0000644000176200001440000000364213167637071015170 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkNull.R \name{checkNull} \alias{checkNull} \alias{check_null} \alias{assertNull} \alias{assert_null} \alias{testNull} \alias{test_null} \title{Check if an argument is NULL} \usage{ checkNull(x) check_null(x) assertNull(x, .var.name = vname(x), add = NULL) assert_null(x, .var.name = vname(x), add = NULL) testNull(x) test_null(x) } \arguments{ \item{x}{[any]\cr Object to check.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertNull}/\code{assert_null} return \code{x} invisibly, whereas \code{checkNull}/\code{check_null} and \code{testNull}/\code{test_null} return \code{TRUE}. If the check is not successful, \code{assertNull}/\code{assert_null} throws an error message, \code{testNull}/\code{test_null} returns \code{FALSE}, and \code{checkNull} returns a string with the error message. The function \code{expect_null} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is NULL } \examples{ testNull(NULL) testNull(1) } \seealso{ Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} } checkmate/man/checkDataFrame.Rd0000644000176200001440000001314213167637071016076 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkDataFrame.R \name{checkDataFrame} \alias{checkDataFrame} \alias{check_data_frame} \alias{assertDataFrame} \alias{assert_data_frame} \alias{testDataFrame} \alias{test_data_frame} \alias{expect_data_frame} \title{Check if an argument is a data frame} \usage{ checkDataFrame(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) check_data_frame(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) assertDataFrame(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_data_frame(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testDataFrame(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) test_data_frame(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) expect_data_frame(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{types}{[\code{character}]\cr Character vector of class names. Each list element must inherit from at least one of the provided types. The types \dQuote{logical}, \dQuote{integer}, \dQuote{integerish}, \dQuote{double}, \dQuote{numeric}, \dQuote{complex}, \dQuote{character}, \dQuote{factor}, \dQuote{atomic}, \dQuote{vector} \dQuote{atomicvector}, \dQuote{array}, \dQuote{matrix}, \dQuote{list}, \dQuote{function}, \dQuote{environment} and \dQuote{null} are supported. For other types \code{\link[base]{inherits}} is used as a fallback to check \code{x}'s inheritance. Defaults to \code{character(0)} (no check).} \item{any.missing}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are matrices with only missing values allowed? Default is \code{TRUE}.} \item{min.rows}{[\code{integer(1)}]\cr Minimum number of rows.} \item{min.cols}{[\code{integer(1)}]\cr Minimum number of columns.} \item{nrows}{[\code{integer(1)}]\cr Exact number of rows.} \item{ncols}{[\code{integer(1)}]\cr Exact number of columns.} \item{row.names}{[\code{character(1)}]\cr Check for row names. Default is \dQuote{NULL} (no check). See \code{\link{checkNamed}} for possible values. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{col.names}{[\code{character(1)}]\cr Check for column names. Default is \dQuote{NULL} (no check). See \code{\link{checkNamed}} for possible values. Note that you can use \code{\link{checkSubset}} to test for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertDataFrame}/\code{assert_data_frame} return \code{x} invisibly, whereas \code{checkDataFrame}/\code{check_data_frame} and \code{testDataFrame}/\code{test_data_frame} return \code{TRUE}. If the check is not successful, \code{assertDataFrame}/\code{assert_data_frame} throws an error message, \code{testDataFrame}/\code{test_data_frame} returns \code{FALSE}, and \code{checkDataFrame} returns a string with the error message. The function \code{expect_data_frame} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a data frame } \examples{ testDataFrame(iris) testDataFrame(iris, types = c("numeric", "factor"), min.rows = 1, col.names = "named") } \seealso{ Other compound: \code{\link{checkArray}}, \code{\link{checkDataTable}}, \code{\link{checkMatrix}}, \code{\link{checkTibble}} Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} } checkmate/man/matchArg.Rd0000644000176200001440000000212613117521632014770 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/matchArg.R \name{matchArg} \alias{matchArg} \title{Partial Argument Matching} \usage{ matchArg(x, choices, several.ok = FALSE, .var.name = vname(x), add = NULL) } \arguments{ \item{x}{[character]\cr User provided argument to match.} \item{choices}{[character()]\cr Candidates to match \code{x} with.} \item{several.ok}{[logical(1)]\cr If \code{TRUE}, multiple matches are allowed, cf. \code{\link[base]{match.arg}}.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in error messages. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertions. See \code{\link{AssertCollection}}.} } \value{ Subset of \code{choices}. } \description{ This is an extensions to \code{\link[base]{match.arg}} with support for \code{\link{AssertCollection}}. The behavior is very similar to \code{\link[base]{match.arg}}, except that \code{NULL} is not a valid value for \code{x}. } \examples{ matchArg("k", choices = c("kendall", "pearson")) } checkmate/man/checkDataTable.Rd0000644000176200001440000001301413047277570016072 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkDataTable.R \name{checkDataTable} \alias{checkDataTable} \alias{check_data_table} \alias{assertDataTable} \alias{assert_data_table} \alias{testDataTable} \alias{test_data_table} \alias{expect_data_table} \title{Check if an argument is a data table} \usage{ checkDataTable(x, key = NULL, index = NULL, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) check_data_table(x, key = NULL, index = NULL, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) assertDataTable(x, key = NULL, index = NULL, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_data_table(x, key = NULL, index = NULL, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testDataTable(x, key = NULL, index = NULL, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) test_data_table(x, key = NULL, index = NULL, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) expect_data_table(x, key = NULL, index = NULL, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{key}{[\code{character}]\cr Expected primary key(s) of the data table.} \item{index}{[\code{character}]\cr Expected secondary key(s) of the data table.} \item{types}{[\code{character}]\cr Character vector of class names. Each list element must inherit from at least one of the provided types. The types \dQuote{logical}, \dQuote{integer}, \dQuote{integerish}, \dQuote{double}, \dQuote{numeric}, \dQuote{complex}, \dQuote{character}, \dQuote{factor}, \dQuote{atomic}, \dQuote{vector} \dQuote{atomicvector}, \dQuote{array}, \dQuote{matrix}, \dQuote{list}, \dQuote{function}, \dQuote{environment} and \dQuote{null} are supported. For other types \code{\link[base]{inherits}} is used as a fallback to check \code{x}'s inheritance. Defaults to \code{character(0)} (no check).} \item{any.missing}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are matrices with only missing values allowed? Default is \code{TRUE}.} \item{min.rows}{[\code{integer(1)}]\cr Minimum number of rows.} \item{min.cols}{[\code{integer(1)}]\cr Minimum number of columns.} \item{nrows}{[\code{integer(1)}]\cr Exact number of rows.} \item{ncols}{[\code{integer(1)}]\cr Exact number of columns.} \item{row.names}{[\code{character(1)}]\cr Check for row names. Default is \dQuote{NULL} (no check). See \code{\link{checkNamed}} for possible values. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{col.names}{[\code{character(1)}]\cr Check for column names. Default is \dQuote{NULL} (no check). See \code{\link{checkNamed}} for possible values. Note that you can use \code{\link{checkSubset}} to test for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertDataTable}/\code{assert_data_table} return \code{x} invisibly, whereas \code{checkDataTable}/\code{check_data_table} and \code{testDataTable}/\code{test_data_table} return \code{TRUE}. If the check is not successful, \code{assertDataTable}/\code{assert_data_table} throws an error message, \code{testDataTable}/\code{test_data_table} returns \code{FALSE}, and \code{checkDataTable} returns a string with the error message. The function \code{expect_data_table} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a data table } \examples{ library(data.table) dt = as.data.table(iris) setkeyv(dt, "Species") setkeyv(dt, "Sepal.Length", physical = FALSE) testDataTable(dt) testDataTable(dt, key = "Species", index = "Sepal.Length", any.missing = FALSE) } \seealso{ Other compound: \code{\link{checkArray}}, \code{\link{checkDataFrame}}, \code{\link{checkMatrix}}, \code{\link{checkTibble}} } checkmate/man/checkScalarNA.Rd0000644000176200001440000000463313047277570015704 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkScalarNA.R \name{checkScalarNA} \alias{checkScalarNA} \alias{check_scalar_na} \alias{assertScalarNA} \alias{assert_scalar_na} \alias{testScalarNA} \alias{test_scalar_na} \alias{expect_scalar_na} \title{Check if an argument is a single missing value} \usage{ checkScalarNA(x, null.ok = FALSE) check_scalar_na(x, null.ok = FALSE) assertScalarNA(x, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_scalar_na(x, null.ok = FALSE, .var.name = vname(x), add = NULL) testScalarNA(x, null.ok = FALSE) test_scalar_na(x, null.ok = FALSE) expect_scalar_na(x, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertScalarNA}/\code{assert_scalar_na} return \code{x} invisibly, whereas \code{checkScalarNA}/\code{check_scalar_na} and \code{testScalarNA}/\code{test_scalar_na} return \code{TRUE}. If the check is not successful, \code{assertScalarNA}/\code{assert_scalar_na} throws an error message, \code{testScalarNA}/\code{test_scalar_na} returns \code{FALSE}, and \code{checkScalarNA} returns a string with the error message. The function \code{expect_scalar_na} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a single missing value } \examples{ testScalarNA(1) testScalarNA(NA_real_) testScalarNA(rep(NA, 2)) } \seealso{ Other scalars: \code{\link{checkCount}}, \code{\link{checkFlag}}, \code{\link{checkInt}}, \code{\link{checkNumber}}, \code{\link{checkScalar}}, \code{\link{checkString}} } checkmate/man/checkSetEqual.Rd0000644000176200001440000000613513167073256016000 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkSetEqual.R \name{checkSetEqual} \alias{checkSetEqual} \alias{check_set_equal} \alias{assertSetEqual} \alias{assert_set_equal} \alias{testSetEqual} \alias{test_set_equal} \alias{expect_set_equal} \title{Check if an argument is equal to a given set} \usage{ checkSetEqual(x, y, ordered = FALSE, fmatch = FALSE) check_set_equal(x, y, ordered = FALSE, fmatch = FALSE) assertSetEqual(x, y, ordered = FALSE, fmatch = FALSE, .var.name = vname(x), add = NULL) assert_set_equal(x, y, ordered = FALSE, fmatch = FALSE, .var.name = vname(x), add = NULL) testSetEqual(x, y, ordered = FALSE, fmatch = FALSE) test_set_equal(x, y, ordered = FALSE, fmatch = FALSE) expect_set_equal(x, y, ordered = FALSE, fmatch = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{y}{[\code{atomic}]\cr Set to compare with.} \item{ordered}{[\code{logical(1)}]\cr Check \code{x} to have the same length and order as \code{y}, i.e. check using \dQuote{==} while handling \code{NA}s nicely. Default is \code{FALSE}.} \item{fmatch}{[\code{logical(1)}]\cr Use the set operations implemented in \code{\link[fastmatch]{fmatch}} in package \pkg{fastmatch}. If \pkg{fastmatch} is not installed, this silently falls back to \code{\link[base]{match}}. \code{\link[fastmatch]{fmatch}} modifies \code{y} by reference: A hash table is added as attribute which is used in subsequent calls.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertSubset}/\code{assert_subset} return \code{x} invisibly, whereas \code{checkSubset}/\code{check_subset} and \code{testSubset}/\code{test_subset} return \code{TRUE}. If the check is not successful, \code{assertSubset}/\code{assert_subset} throws an error message, \code{testSubset}/\code{test_subset} returns \code{FALSE}, and \code{checkSubset} returns a string with the error message. The function \code{expect_subset} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is equal to a given set } \note{ The object \code{x} must be of the same type as the set w.r.t. \code{\link[base]{typeof}}. Integers and doubles are both treated as numeric. } \examples{ testSetEqual(c("a", "b"), c("a", "b")) testSetEqual(1:3, 1:4) # x is not converted before the comparison (except for numerics) testSetEqual(factor("a"), "a") testSetEqual(1, "1") testSetEqual(1, as.integer(1)) } \seealso{ Other set: \code{\link{checkChoice}}, \code{\link{checkSubset}} } checkmate/man/checkClass.Rd0000644000176200001440000000564713160423672015323 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkClass.R \name{checkClass} \alias{checkClass} \alias{check_class} \alias{assertClass} \alias{assert_class} \alias{testClass} \alias{test_class} \alias{expect_class} \title{Check the class membership of an argument} \usage{ checkClass(x, classes, ordered = FALSE, null.ok = FALSE) check_class(x, classes, ordered = FALSE, null.ok = FALSE) assertClass(x, classes, ordered = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_class(x, classes, ordered = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL) testClass(x, classes, ordered = FALSE, null.ok = FALSE) test_class(x, classes, ordered = FALSE, null.ok = FALSE) expect_class(x, classes, ordered = FALSE, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{classes}{[\code{character}]\cr Class names to check for inheritance with \code{\link[base]{inherits}}.} \item{ordered}{[\code{logical(1)}]\cr Expect \code{x} to be specialized in provided order. Default is \code{FALSE}.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertClass}/\code{assert_class} return \code{x} invisibly, whereas \code{checkClass}/\code{check_class} and \code{testClass}/\code{test_class} return \code{TRUE}. If the check is not successful, \code{assertClass}/\code{assert_class} throws an error message, \code{testClass}/\code{test_class} returns \code{FALSE}, and \code{checkClass} returns a string with the error message. The function \code{expect_class} always returns an \code{\link[testthat]{expectation}}. } \description{ Check the class membership of an argument } \examples{ # Create an object with classes "foo" and "bar" x = 1 class(x) = c("foo", "bar") # is x of class "foo"? testClass(x, "foo") # is x of class "foo" and "bar"? testClass(x, c("foo", "bar")) # is x of class "foo" or "bar"? \dontrun{ assert( checkClass(x, "foo"), checkClass(x, "bar") ) } # is x most specialized as "bar"? testClass(x, "bar", ordered = TRUE) } \seealso{ \code{\link{checkR6}} Other attributes: \code{\link{checkNamed}}, \code{\link{checkNames}} } checkmate/man/checkCount.Rd0000644000176200001440000000661413117521632015336 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkCount.R \name{checkCount} \alias{checkCount} \alias{check_count} \alias{assertCount} \alias{assert_count} \alias{testCount} \alias{test_count} \alias{expect_count} \title{Check if an argument is a count} \usage{ checkCount(x, na.ok = FALSE, positive = FALSE, tol = sqrt(.Machine$double.eps), null.ok = FALSE) check_count(x, na.ok = FALSE, positive = FALSE, tol = sqrt(.Machine$double.eps), null.ok = FALSE) assertCount(x, na.ok = FALSE, positive = FALSE, tol = sqrt(.Machine$double.eps), null.ok = FALSE, .var.name = vname(x), add = NULL) assert_count(x, na.ok = FALSE, positive = FALSE, tol = sqrt(.Machine$double.eps), null.ok = FALSE, .var.name = vname(x), add = NULL) testCount(x, na.ok = FALSE, positive = FALSE, tol = sqrt(.Machine$double.eps), null.ok = FALSE) test_count(x, na.ok = FALSE, positive = FALSE, tol = sqrt(.Machine$double.eps), null.ok = FALSE) expect_count(x, na.ok = FALSE, positive = FALSE, tol = sqrt(.Machine$double.eps), null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{na.ok}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{FALSE}.} \item{positive}{[\code{logical(1)}]\cr Must \code{x} be positive (>= 1)? Default is \code{FALSE}, allowing 0.} \item{tol}{[\code{double(1)}]\cr Numerical tolerance used to check whether a double or complex can be converted. Default is \code{sqrt(.Machine$double.eps)}.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertCount}/\code{assert_count} return \code{x} invisibly, whereas \code{checkCount}/\code{check_count} and \code{testCount}/\code{test_count} return \code{TRUE}. If the check is not successful, \code{assertCount}/\code{assert_count} throws an error message, \code{testCount}/\code{test_count} returns \code{FALSE}, and \code{checkCount} returns a string with the error message. The function \code{expect_count} always returns an \code{\link[testthat]{expectation}}. } \description{ A count is defined as non-negative integerish value. } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \note{ To perform an assertion and then convert to integer, use \code{\link{asCount}}. \code{assertCount} will not convert numerics to integer. } \examples{ testCount(1) testCount(-1) } \seealso{ Other scalars: \code{\link{checkFlag}}, \code{\link{checkInt}}, \code{\link{checkNumber}}, \code{\link{checkScalarNA}}, \code{\link{checkScalar}}, \code{\link{checkString}} } checkmate/man/checkComplex.Rd0000644000176200001440000001063713167637071015667 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkComplex.R \name{checkComplex} \alias{checkComplex} \alias{check_complex} \alias{assertComplex} \alias{assert_complex} \alias{testComplex} \alias{test_complex} \alias{expect_complex} \title{Check if an argument is a vector of type complex} \usage{ checkComplex(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) check_complex(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) assertComplex(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_complex(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testComplex(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) test_complex(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) expect_complex(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertComplex}/\code{assert_complex} return \code{x} invisibly, whereas \code{checkComplex}/\code{check_complex} and \code{testComplex}/\code{test_complex} return \code{TRUE}. If the check is not successful, \code{assertComplex}/\code{assert_complex} throws an error message, \code{testComplex}/\code{test_complex} returns \code{FALSE}, and \code{checkComplex} returns a string with the error message. The function \code{expect_complex} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a vector of type complex } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testComplex(1) testComplex(1+1i) } \seealso{ Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} } checkmate/man/checkInt.Rd0000644000176200001440000000676713117521632015011 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkInt.R \name{checkInt} \alias{checkInt} \alias{check_int} \alias{assertInt} \alias{assert_int} \alias{testInt} \alias{test_int} \alias{expect_int} \title{Check if an argument is a single integerish value} \usage{ checkInt(x, na.ok = FALSE, lower = -Inf, upper = Inf, tol = sqrt(.Machine$double.eps), null.ok = FALSE) check_int(x, na.ok = FALSE, lower = -Inf, upper = Inf, tol = sqrt(.Machine$double.eps), null.ok = FALSE) assertInt(x, na.ok = FALSE, lower = -Inf, upper = Inf, tol = sqrt(.Machine$double.eps), null.ok = FALSE, .var.name = vname(x), add = NULL) assert_int(x, na.ok = FALSE, lower = -Inf, upper = Inf, tol = sqrt(.Machine$double.eps), null.ok = FALSE, .var.name = vname(x), add = NULL) testInt(x, na.ok = FALSE, lower = -Inf, upper = Inf, tol = sqrt(.Machine$double.eps), null.ok = FALSE) test_int(x, na.ok = FALSE, lower = -Inf, upper = Inf, tol = sqrt(.Machine$double.eps), null.ok = FALSE) expect_int(x, na.ok = FALSE, lower = -Inf, upper = Inf, tol = sqrt(.Machine$double.eps), null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{na.ok}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{FALSE}.} \item{lower}{[\code{numeric(1)}]\cr Lower value all elements of \code{x} must be greater than.} \item{upper}{[\code{numeric(1)}]\cr Upper value all elements of \code{x} must be lower than.} \item{tol}{[\code{double(1)}]\cr Numerical tolerance used to check whether a double or complex can be converted. Default is \code{sqrt(.Machine$double.eps)}.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertInt}/\code{assert_int} return \code{x} invisibly, whereas \code{checkInt}/\code{check_int} and \code{testInt}/\code{test_int} return \code{TRUE}. If the check is not successful, \code{assertInt}/\code{assert_int} throws an error message, \code{testInt}/\code{test_int} returns \code{FALSE}, and \code{checkInt} returns a string with the error message. The function \code{expect_int} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a single integerish value } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \note{ To perform an assertion and then convert to integer, use \code{\link{asInt}}. \code{assertInt} will not convert numerics to integer. } \examples{ testInt(1) testInt(-1, lower = 0) } \seealso{ Other scalars: \code{\link{checkCount}}, \code{\link{checkFlag}}, \code{\link{checkNumber}}, \code{\link{checkScalarNA}}, \code{\link{checkScalar}}, \code{\link{checkString}} } checkmate/man/qassertr.Rd0000644000176200001440000000364313047277570015126 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/qassertr.R \name{qassertr} \alias{qassertr} \alias{qtestr} \alias{qexpectr} \title{Quick recursive arguments checks on lists and data frames} \usage{ qassertr(x, rules, .var.name = vname(x)) qtestr(x, rules, depth = 1L) qexpectr(x, rules, info = NULL, label = vname(x)) } \arguments{ \item{x}{[\code{list} or \code{data.frame}]\cr List or data frame to check for compliance with at least one of \code{rules}. See details of \code{\link{qtest}} for rule explanation.} \item{rules}{[\code{character}]\cr Set of rules. See \code{\link{qtest}}} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in error messages. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{depth}{[\code{integer(1)}]\cr Maximum recursion depth. Defaults to \dQuote{1} to directly check list elements or data frame columns. Set to a higher value to check lists of lists of elements.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ See \code{\link{qassert}}. } \description{ These functions are the tuned counterparts of \code{\link{qtest}}, \code{\link{qassert}} and \code{\link{qexpect}} tailored for recursive checks of list elements or data frame columns. } \examples{ # All list elements are integers with length >= 1? qtestr(as.list(1:10), "i+") # All list elements (i.e. data frame columns) are numeric? qtestr(iris, "n") # All list elements are numeric, w/o NAs? qtestr(list(a = 1:3, b = rnorm(1), c = letters), "N+") # All list elements are numeric OR character qtestr(list(a = 1:3, b = rnorm(1), c = letters), c("N+", "S+")) } \seealso{ \code{\link{qtest}}, \code{\link{qassert}} } checkmate/man/checkVector.Rd0000644000176200001440000001125313167637071015515 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkVector.R \name{checkVector} \alias{checkVector} \alias{check_vector} \alias{assertVector} \alias{assert_vector} \alias{testVector} \alias{test_vector} \alias{expect_vector} \title{Check if an argument is a vector} \usage{ checkVector(x, strict = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) check_vector(x, strict = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) assertVector(x, strict = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_vector(x, strict = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testVector(x, strict = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) test_vector(x, strict = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) expect_vector(x, strict = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{strict}{[\code{logical(1)}]\cr May the vector have additional attributes or perform a check for additional attributes like \code{\link[base]{is.vector}}? Default is \code{FALSE} which allows e.g. \code{factor}s or \code{data.frame}s to be recognized as vectors.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertVector}/\code{assert_vector} return \code{x} invisibly, whereas \code{checkVector}/\code{check_vector} and \code{testVector}/\code{test_vector} return \code{TRUE}. If the check is not successful, \code{assertVector}/\code{assert_vector} throws an error message, \code{testVector}/\code{test_vector} returns \code{FALSE}, and \code{checkVector} returns a string with the error message. The function \code{expect_vector} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a vector } \examples{ testVector(letters, min.len = 1L, any.missing = FALSE) } \seealso{ Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}} Other atomicvector: \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}} } checkmate/man/checkEnvironment.Rd0000644000176200001440000000621513167637071016561 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkEnvironment.R \name{checkEnvironment} \alias{checkEnvironment} \alias{check_environment} \alias{assertEnvironment} \alias{assert_environment} \alias{testEnvironment} \alias{test_environment} \alias{expect_environment} \title{Check if an argument is an environment} \usage{ checkEnvironment(x, contains = character(0L), null.ok = FALSE) check_environment(x, contains = character(0L), null.ok = FALSE) assertEnvironment(x, contains = character(0L), null.ok = FALSE, .var.name = vname(x), add = NULL) assert_environment(x, contains = character(0L), null.ok = FALSE, .var.name = vname(x), add = NULL) testEnvironment(x, contains = character(0L), null.ok = FALSE) test_environment(x, contains = character(0L), null.ok = FALSE) expect_environment(x, contains = character(0L), null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{contains}{[\code{character}]\cr Vector of object names expected in the environment. Defaults to \code{character(0)}.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertEnvironment}/\code{assert_environment} return \code{x} invisibly, whereas \code{checkEnvironment}/\code{check_environment} and \code{testEnvironment}/\code{test_environment} return \code{TRUE}. If the check is not successful, \code{assertEnvironment}/\code{assert_environment} throws an error message, \code{testEnvironment}/\code{test_environment} returns \code{FALSE}, and \code{checkEnvironment} returns a string with the error message. The function \code{expect_environment} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is an environment } \examples{ ee = as.environment(list(a = 1)) testEnvironment(ee) testEnvironment(ee, contains = "a") } \seealso{ Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} } checkmate/man/makeTest.Rd0000644000176200001440000000370713047277570015040 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/makeTest.R \name{makeTest} \alias{makeTest} \alias{makeTestFunction} \title{Turn a Check into a Test} \usage{ makeTest(res) makeTestFunction(check.fun, c.fun = NULL, env = parent.frame()) } \arguments{ \item{res}{[\code{TRUE} | \code{character(1)}]\cr The result of a check function: \code{TRUE} for successful checks, and an error message as string otherwise.} \item{check.fun}{[\code{function}]\cr Function which checks the input. Must return \code{TRUE} on success and a string with the error message otherwise.} \item{c.fun}{[\code{character(1)}]\cr If not \code{NULL}, instead of calling the function \code{check.fun}, use \code{.Call} to call a C function \dQuote{c.fun} with the identical set of parameters. The C function must be registered as a native symbol, see \code{\link[base]{.Call}}. Useful if \code{check.fun} is just a simple wrapper.} \item{env}{[\code{environment}]\cr The environment of the created function. Default is the \code{\link[base]{parent.frame}}.} } \value{ \code{makeTest} returns \code{TRUE} if the check is successful and \code{FALSE} otherwise. \code{makeTestFunction} returns a \code{function}. } \description{ \code{makeTest} is the internal function used to evaluate the result of a check and throw an exception if necessary. This function is currently only a stub and just calls \code{\link[base]{isTRUE}}. \code{makeTestFunction} can be used to automatically create an assertion function based on a check function (see example). } \examples{ # Simple custom check function checkFalse = function(x) if (!identical(x, FALSE)) "Must be FALSE" else TRUE # Create the respective test function testFalse = function(x) { res = checkFalse(x) makeTest(res) } # Alternative: Automatically create such a function testFalse = makeTestFunction(checkFalse) print(testFalse) } \seealso{ Other CustomConstructors: \code{\link{makeAssertion}}, \code{\link{makeExpectation}} } checkmate/man/checkSubset.Rd0000644000176200001440000000616713167073256015527 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkSubset.R \name{checkSubset} \alias{checkSubset} \alias{check_subset} \alias{assertSubset} \alias{assert_subset} \alias{testSubset} \alias{test_subset} \alias{expect_subset} \title{Check if an argument is a subset of a given set} \usage{ checkSubset(x, choices, empty.ok = TRUE, fmatch = FALSE) check_subset(x, choices, empty.ok = TRUE, fmatch = FALSE) assertSubset(x, choices, empty.ok = TRUE, fmatch = FALSE, .var.name = vname(x), add = NULL) assert_subset(x, choices, empty.ok = TRUE, fmatch = FALSE, .var.name = vname(x), add = NULL) testSubset(x, choices, empty.ok = TRUE, fmatch = FALSE) test_subset(x, choices, empty.ok = TRUE, fmatch = FALSE) expect_subset(x, choices, empty.ok = TRUE, fmatch = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{choices}{[\code{atomic}]\cr Set of possible values. May be empty.} \item{empty.ok}{[\code{logical(1)}]\cr Treat zero-length \code{x} as subset of any set \code{choices} (this includes \code{NULL})? Default is \code{TRUE}.} \item{fmatch}{[\code{logical(1)}]\cr Use the set operations implemented in \code{\link[fastmatch]{fmatch}} in package \pkg{fastmatch}. If \pkg{fastmatch} is not installed, this silently falls back to \code{\link[base]{match}}. \code{\link[fastmatch]{fmatch}} modifies \code{y} by reference: A hash table is added as attribute which is used in subsequent calls.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertSubset}/\code{assert_subset} return \code{x} invisibly, whereas \code{checkSubset}/\code{check_subset} and \code{testSubset}/\code{test_subset} return \code{TRUE}. If the check is not successful, \code{assertSubset}/\code{assert_subset} throws an error message, \code{testSubset}/\code{test_subset} returns \code{FALSE}, and \code{checkSubset} returns a string with the error message. The function \code{expect_subset} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a subset of a given set } \note{ The object \code{x} must be of the same type as the set w.r.t. \code{\link[base]{typeof}}. Integers and doubles are both treated as numeric. } \examples{ testSubset(c("a", "z"), letters) testSubset("ab", letters) testSubset("Species", names(iris)) # x is not converted before the comparison (except for numerics) testSubset(factor("a"), "a") testSubset(1, "1") testSubset(1, as.integer(1)) } \seealso{ Other set: \code{\link{checkChoice}}, \code{\link{checkSetEqual}} } checkmate/man/checkOS.Rd0000644000176200001440000000343513047277570014600 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkOS.R \name{checkOS} \alias{checkOS} \alias{check_os} \alias{assertOS} \alias{assert_os} \alias{testOS} \alias{test_os} \alias{expect_os} \title{Check the operating system} \usage{ checkOS(os) check_os(os) assertOS(os, add = NULL, .var.name = NULL) assert_os(os, add = NULL, .var.name = NULL) testOS(os) test_os(os) expect_os(os, info = NULL, label = NULL) } \arguments{ \item{os}{[\code{character(1)}]\cr Check the operating system to be in a set with possible elements \dQuote{windows}, \dQuote{mac}, \dQuote{linux} and \dQuote{solaris}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertOS}/\code{assert_os} return \code{x} invisibly, whereas \code{checkOS}/\code{check_os} and \code{testOS}/\code{test_os} return \code{TRUE}. If the check is not successful, \code{assertOS}/\code{assert_os} throws an error message, \code{testOS}/\code{test_os} returns \code{FALSE}, and \code{checkOS} returns a string with the error message. The function \code{expect_os} always returns an \code{\link[testthat]{expectation}}. } \description{ Check the operating system } \examples{ testOS("linux") } checkmate/man/checkmate-package.Rd0000644000176200001440000000564413162404132016562 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/zzz.R \docType{package} \name{checkmate-package} \alias{checkmate} \alias{checkmate-package} \title{checkmate: Fast and Versatile Argument Checks} \description{ \describe{ \item{Homepage:}{\url{https://github.com/mllg/checkmate}} \item{Bug Reports:}{\url{https://github.com/mllg/checkmate/issues}} } } \section{Overview of implemented functions}{ Check scalars: \itemize{ \item{\code{\link{checkFlag}}} \item{\code{\link{checkCount}}} \item{\code{\link{checkNumber}}} \item{\code{\link{checkInt}}} \item{\code{\link{checkString}}} \item{\code{\link{checkScalar}}} \item{\code{\link{checkScalarNA}}} } Check vectors: \itemize{ \item{\code{\link{checkLogical}}} \item{\code{\link{checkNumeric}}} \item{\code{\link{checkInteger}}} \item{\code{\link{checkIntegerish}}} \item{\code{\link{checkCharacter}}} \item{\code{\link{checkComplex}}} \item{\code{\link{checkFactor}}} \item{\code{\link{checkList}}} \item{\code{\link{checkVector}}} \item{\code{\link{checkAtomic}}} \item{\code{\link{checkAtomicVector}}} } Check attributes: \itemize{ \item{\code{\link{checkClass}}} \item{\code{\link{checkNames}}} \item{\code{\link{checkNamed}}} (deprecated) } Check compound types: \itemize{ \item{\code{\link{checkArray}}} \item{\code{\link{checkDataFrame}}} \item{\code{\link{checkMatrix}}} } Check other built-in R types: \itemize{ \item{\code{\link{checkDate}}} \item{\code{\link{checkEnvironment}}} \item{\code{\link{checkFunction}}} \item{\code{\link{checkNull}}} } Check sets: \itemize{ \item{\code{\link{checkChoice}}} \item{\code{\link{checkSubset}}} \item{\code{\link{checkSetEqual}}} } File IO: \itemize{ \item{\code{\link{checkFileExists}}} \item{\code{\link{checkDirectoryExists}}} \item{\code{\link{checkPathForOutput}}} \item{\code{\link{checkAccess}}} } Popular data types in external packages: \itemize{ \item{\code{\link{checkBit}}} \item{\code{\link{checkDataTable}}} \item{\code{\link{checkR6}}} \item{\code{\link{checkTibble}}} } Safe coercion to integer: \itemize{ \item{\code{\link{asCount}}} \item{\code{\link{asInt}}} \item{\code{\link{asInteger}}} } Quick argument checks using a DSL: \itemize{ \item{\code{\link{qassert}}} \item{\code{\link{qassertr}}} } Misc: \itemize{ \item{\code{\link{checkOS}} (check operating system)} \item{\code{\link{assert}} (combine multiple checks into an assertion)} \item{\code{\link{anyMissing}}} \item{\code{\link{allMissing}}} \item{\code{\link{anyNaN}}} \item{\code{\link{wf}} (which.first and which.last)} } } \seealso{ Useful links: \itemize{ \item \url{https://github.com/mllg/checkmate} \item Report bugs at \url{https://github.com/mllg/checkmate/issues} } } \author{ \strong{Maintainer}: Michel Lang \email{michellang@gmail.com} Other contributors: \itemize{ \item Bernd Bischl \email{bernd_bischl@gmx.de} [contributor] } } checkmate/man/checkScalar.Rd0000644000176200001440000000523513047277570015464 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkScalar.R \name{checkScalar} \alias{checkScalar} \alias{check_scalar} \alias{assertScalar} \alias{assert_scalar} \alias{testScalar} \alias{test_scalar} \alias{expect_scalar} \title{Check if an argument is a single atomic value} \usage{ checkScalar(x, na.ok = FALSE, null.ok = FALSE) check_scalar(x, na.ok = FALSE, null.ok = FALSE) assertScalar(x, na.ok = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_scalar(x, na.ok = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL) testScalar(x, na.ok = FALSE, null.ok = FALSE) test_scalar(x, na.ok = FALSE, null.ok = FALSE) expect_scalar(x, na.ok = FALSE, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{na.ok}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{FALSE}.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertScalar}/\code{assert_scalar} return \code{x} invisibly, whereas \code{checkScalar}/\code{check_scalar} and \code{testScalar}/\code{test_scalar} return \code{TRUE}. If the check is not successful, \code{assertScalar}/\code{assert_scalar} throws an error message, \code{testScalar}/\code{test_scalar} returns \code{FALSE}, and \code{checkScalar} returns a string with the error message. The function \code{expect_scalar} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a single atomic value } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testScalar(1) testScalar(1:10) } \seealso{ Other scalars: \code{\link{checkCount}}, \code{\link{checkFlag}}, \code{\link{checkInt}}, \code{\link{checkNumber}}, \code{\link{checkScalarNA}}, \code{\link{checkString}} } checkmate/man/checkNumber.Rd0000644000176200001440000000636113047277570015510 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkNumber.R \name{checkNumber} \alias{checkNumber} \alias{check_number} \alias{assertNumber} \alias{assert_number} \alias{testNumber} \alias{test_number} \alias{expect_number} \title{Check if an argument is a single numeric value} \usage{ checkNumber(x, na.ok = FALSE, lower = -Inf, upper = Inf, finite = FALSE, null.ok = FALSE) check_number(x, na.ok = FALSE, lower = -Inf, upper = Inf, finite = FALSE, null.ok = FALSE) assertNumber(x, na.ok = FALSE, lower = -Inf, upper = Inf, finite = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_number(x, na.ok = FALSE, lower = -Inf, upper = Inf, finite = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL) testNumber(x, na.ok = FALSE, lower = -Inf, upper = Inf, finite = FALSE, null.ok = FALSE) test_number(x, na.ok = FALSE, lower = -Inf, upper = Inf, finite = FALSE, null.ok = FALSE) expect_number(x, na.ok = FALSE, lower = -Inf, upper = Inf, finite = FALSE, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{na.ok}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{FALSE}.} \item{lower}{[\code{numeric(1)}]\cr Lower value all elements of \code{x} must be greater than.} \item{upper}{[\code{numeric(1)}]\cr Upper value all elements of \code{x} must be lower than.} \item{finite}{[\code{logical(1)}]\cr Check for only finite values? Default is \code{FALSE}.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertNumber}/\code{assert_number} return \code{x} invisibly, whereas \code{checkNumber}/\code{check_number} and \code{testNumber}/\code{test_number} return \code{TRUE}. If the check is not successful, \code{assertNumber}/\code{assert_number} throws an error message, \code{testNumber}/\code{test_number} returns \code{FALSE}, and \code{checkNumber} returns a string with the error message. The function \code{expect_number} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a single numeric value } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testNumber(1) testNumber(1:2) } \seealso{ Other scalars: \code{\link{checkCount}}, \code{\link{checkFlag}}, \code{\link{checkInt}}, \code{\link{checkScalarNA}}, \code{\link{checkScalar}}, \code{\link{checkString}} } checkmate/man/checkFlag.Rd0000644000176200001440000000512113047277570015122 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkFlag.R \name{checkFlag} \alias{checkFlag} \alias{check_flag} \alias{assertFlag} \alias{assert_flag} \alias{testFlag} \alias{test_flag} \alias{expect_flag} \title{Check if an argument is a flag} \usage{ checkFlag(x, na.ok = FALSE, null.ok = FALSE) check_flag(x, na.ok = FALSE, null.ok = FALSE) assertFlag(x, na.ok = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_flag(x, na.ok = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL) testFlag(x, na.ok = FALSE, null.ok = FALSE) test_flag(x, na.ok = FALSE, null.ok = FALSE) expect_flag(x, na.ok = FALSE, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{na.ok}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{FALSE}.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertFlag}/\code{assert_flag} return \code{x} invisibly, whereas \code{checkFlag}/\code{check_flag} and \code{testFlag}/\code{test_flag} return \code{TRUE}. If the check is not successful, \code{assertFlag}/\code{assert_flag} throws an error message, \code{testFlag}/\code{test_flag} returns \code{FALSE}, and \code{checkFlag} returns a string with the error message. The function \code{expect_flag} always returns an \code{\link[testthat]{expectation}}. } \description{ A flag is defined as single logical value. } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testFlag(TRUE) testFlag(1) } \seealso{ Other scalars: \code{\link{checkCount}}, \code{\link{checkInt}}, \code{\link{checkNumber}}, \code{\link{checkScalarNA}}, \code{\link{checkScalar}}, \code{\link{checkString}} } checkmate/man/checkInteger.Rd0000644000176200001440000001211713167637071015650 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkInteger.R \name{checkInteger} \alias{checkInteger} \alias{check_integer} \alias{assertInteger} \alias{assert_integer} \alias{testInteger} \alias{test_integer} \alias{expect_integer} \title{Check if an argument is vector of type integer} \usage{ checkInteger(x, lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) check_integer(x, lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) assertInteger(x, lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_integer(x, lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testInteger(x, lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) test_integer(x, lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) expect_integer(x, lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{lower}{[\code{numeric(1)}]\cr Lower value all elements of \code{x} must be greater than.} \item{upper}{[\code{numeric(1)}]\cr Upper value all elements of \code{x} must be lower than.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{sorted}{[\code{logical(1)}]\cr Elements must be sorted in ascending order. Missing values are ignored.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertInteger}/\code{assert_integer} return \code{x} invisibly, whereas \code{checkInteger}/\code{check_integer} and \code{testInteger}/\code{test_integer} return \code{TRUE}. If the check is not successful, \code{assertInteger}/\code{assert_integer} throws an error message, \code{testInteger}/\code{test_integer} returns \code{FALSE}, and \code{checkInteger} returns a string with the error message. The function \code{expect_integer} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is vector of type integer } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testInteger(1L) testInteger(1.) testInteger(1:2, lower = 1, upper = 2, any.missing = FALSE) } \seealso{ \code{\link{asInteger}} Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} } checkmate/man/checkList.Rd0000644000176200001440000001260013167637071015163 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkList.R \name{checkList} \alias{checkList} \alias{check_list} \alias{assertList} \alias{assert_list} \alias{testList} \alias{test_list} \alias{expect_list} \title{Check if an argument is a list} \usage{ checkList(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) check_list(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) assertList(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_list(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testList(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) test_list(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) expect_list(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{types}{[\code{character}]\cr Character vector of class names. Each list element must inherit from at least one of the provided types. The types \dQuote{logical}, \dQuote{integer}, \dQuote{integerish}, \dQuote{double}, \dQuote{numeric}, \dQuote{complex}, \dQuote{character}, \dQuote{factor}, \dQuote{atomic}, \dQuote{vector} \dQuote{atomicvector}, \dQuote{array}, \dQuote{matrix}, \dQuote{list}, \dQuote{function}, \dQuote{environment} and \dQuote{null} are supported. For other types \code{\link[base]{inherits}} is used as a fallback to check \code{x}'s inheritance. Defaults to \code{character(0)} (no check).} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{...}{[any]\cr Additional parameters used in a call of \code{\link{checkVector}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertList}/\code{assert_list} return \code{x} invisibly, whereas \code{checkList}/\code{check_list} and \code{testList}/\code{test_list} return \code{TRUE}. If the check is not successful, \code{assertList}/\code{assert_list} throws an error message, \code{testList}/\code{test_list} returns \code{FALSE}, and \code{checkList} returns a string with the error message. The function \code{expect_list} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a list } \note{ The test for uniqueness does differentiate between the different NA types in R. This is require to be consistent with \code{\link[base]{unique}} while checking scalar missing values. Also see the example. } \examples{ testList(list()) testList(as.list(iris), types = c("numeric", "factor")) # Uniqueness differentiates between different NA types: testList(list(NA, NA), unique = TRUE) testList(list(NA, NA_real_), unique = TRUE) } \seealso{ Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} } checkmate/man/coalesce.Rd0000644000176200001440000000117613047277570015037 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/coalesce.R \name{\%??\%} \alias{\%??\%} \title{Coalesce operator} \usage{ lhs \%??\% rhs } \arguments{ \item{lhs}{[any]\cr Left hand side of the operator. Is returned if not missing or \code{NULL}.} \item{rhs}{[any]\cr Right hand side of the operator. Is returned if \code{lhs} is missing or \code{NULL}.} } \value{ Either \code{lhs} or \code{rhs}. } \description{ Returns the left hand side if not missing nor \code{NULL}, and the right hand side otherwise. } \examples{ print(NULL \%??\% 1 \%??\% 2) print(names(iris) \%??\% letters[seq_len(ncol(iris))]) } checkmate/man/checkMatrix.Rd0000644000176200001440000001225213167637071015517 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkMatrix.R \name{checkMatrix} \alias{checkMatrix} \alias{check_matrix} \alias{assertMatrix} \alias{assert_matrix} \alias{testMatrix} \alias{test_matrix} \alias{expect_matrix} \title{Check if an argument is a matrix} \usage{ checkMatrix(x, mode = NULL, any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) check_matrix(x, mode = NULL, any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) assertMatrix(x, mode = NULL, any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_matrix(x, mode = NULL, any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testMatrix(x, mode = NULL, any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) test_matrix(x, mode = NULL, any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) expect_matrix(x, mode = NULL, any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{mode}{[\code{character(1)}]\cr Storage mode of the array. Arrays can hold vectors, i.e. \dQuote{logical}, \dQuote{integer}, \dQuote{integerish}, \dQuote{double}, \dQuote{numeric}, \dQuote{complex}, \dQuote{character} and \dQuote{list}. You can also specify \dQuote{atomic} here to explicitly prohibit lists. Default is \code{NULL} (no check).} \item{any.missing}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are matrices with only missing values allowed? Default is \code{TRUE}.} \item{min.rows}{[\code{integer(1)}]\cr Minimum number of rows.} \item{min.cols}{[\code{integer(1)}]\cr Minimum number of columns.} \item{nrows}{[\code{integer(1)}]\cr Exact number of rows.} \item{ncols}{[\code{integer(1)}]\cr Exact number of columns.} \item{row.names}{[\code{character(1)}]\cr Check for row names. Default is \dQuote{NULL} (no check). See \code{\link{checkNamed}} for possible values. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{col.names}{[\code{character(1)}]\cr Check for column names. Default is \dQuote{NULL} (no check). See \code{\link{checkNamed}} for possible values. Note that you can use \code{\link{checkSubset}} to test for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertMatrix}/\code{assert_matrix} return \code{x} invisibly, whereas \code{checkMatrix}/\code{check_matrix} and \code{testMatrix}/\code{test_matrix} return \code{TRUE}. If the check is not successful, \code{assertMatrix}/\code{assert_matrix} throws an error message, \code{testMatrix}/\code{test_matrix} returns \code{FALSE}, and \code{checkMatrix} returns a string with the error message. The function \code{expect_matrix} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a matrix } \examples{ x = matrix(1:9, 3) colnames(x) = letters[1:3] testMatrix(x, nrows = 3, min.cols = 1, col.names = "named") } \seealso{ Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} Other compound: \code{\link{checkArray}}, \code{\link{checkDataFrame}}, \code{\link{checkDataTable}}, \code{\link{checkTibble}} } checkmate/man/checkR6.Rd0000644000176200001440000000647613160423672014546 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkR6.R \name{checkR6} \alias{checkR6} \alias{check_r6} \alias{assertR6} \alias{assert_r6} \alias{testR6} \alias{test_r6} \alias{expect_r6} \title{Check if an argument is a R6 class} \usage{ checkR6(x, classes = NULL, ordered = FALSE, cloneable = NULL, public = NULL, private = NULL, null.ok = FALSE) check_r6(x, classes = NULL, ordered = FALSE, cloneable = NULL, public = NULL, private = NULL, null.ok = FALSE) assertR6(x, classes = NULL, ordered = FALSE, cloneable = NULL, public = NULL, private = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_r6(x, classes = NULL, ordered = FALSE, cloneable = NULL, public = NULL, private = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testR6(x, classes = NULL, ordered = FALSE, cloneable = NULL, public = NULL, private = NULL, null.ok = FALSE) test_r6(x, classes = NULL, ordered = FALSE, cloneable = NULL, public = NULL, private = NULL, null.ok = FALSE) expect_r6(x, classes = NULL, ordered = FALSE, cloneable = NULL, public = NULL, private = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{classes}{[\code{character}]\cr Class names to check for inheritance with \code{\link[base]{inherits}}.} \item{ordered}{[\code{logical(1)}]\cr Expect \code{x} to be specialized in provided order. Default is \code{FALSE}.} \item{cloneable}{[\code{logical(1)}]\cr If \code{TRUE}, check that \code{x} has a \code{clone} method. If \code{FALSE}, ensure that \code{x} is not cloneable.} \item{public}{[\code{character}]\cr Names of expected public slots. This includes active bindings.} \item{private}{[\code{character}]\cr Names of expected private slots.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertClass}/\code{assert_class} return \code{x} invisibly, whereas \code{checkClass}/\code{check_class} and \code{testClass}/\code{test_class} return \code{TRUE}. If the check is not successful, \code{assertClass}/\code{assert_class} throws an error message, \code{testClass}/\code{test_class} returns \code{FALSE}, and \code{checkClass} returns a string with the error message. The function \code{expect_class} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a R6 class } \examples{ library(R6) generator = R6Class("Bar", public = list(a = 5), private = list(b = 42), active = list(c = function() 99) ) x = generator$new() checkR6(x, "Bar", cloneable = TRUE, public = "a") } checkmate/man/checkFALSE.Rd0000644000176200001440000000315013047277570015103 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkFALSE.R \name{checkFALSE} \alias{checkFALSE} \alias{check_false} \alias{assertFALSE} \alias{assert_false} \alias{testFALSE} \alias{test_false} \title{Check if an argument is FALSE} \usage{ checkFALSE(x, na.ok = FALSE) check_false(x, na.ok = FALSE) assertFALSE(x, na.ok = FALSE, .var.name = vname(x), add = NULL) assert_false(x, na.ok = FALSE, .var.name = vname(x), add = NULL) testFALSE(x, na.ok = FALSE) test_false(x, na.ok = FALSE) } \arguments{ \item{x}{[any]\cr Object to check.} \item{na.ok}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{FALSE}.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertFALSE.}/\code{assert_false.} return \code{x} invisibly, whereas \code{checkFALSE.}/\code{check_false.} and \code{testFALSE.}/\code{test_false.} return \code{TRUE}. If the check is not successful, \code{assertFALSE.}/\code{assert_false.} throws an error message, \code{testFALSE.}/\code{test_false.} returns \code{FALSE}, and \code{checkFALSE.} returns a string with the error message. The function \code{expect_false.} always returns an \code{\link[testthat]{expectation}}. } \description{ Simply checks if an argument is \code{FALSE}. } \examples{ testFALSE(FALSE) testFALSE(TRUE) } checkmate/man/makeExpectation.Rd0000644000176200001440000000432713047277570016403 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/makeExpectation.R \name{makeExpectation} \alias{makeExpectation} \alias{makeExpectationFunction} \title{Turn a Check into an Expectation} \usage{ makeExpectation(x, res, info, label) makeExpectationFunction(check.fun, c.fun = NULL, env = parent.frame()) } \arguments{ \item{x}{[any]\cr Object to check.} \item{res}{[\code{TRUE} | \code{character(1)}]\cr The result of a check function: \code{TRUE} for successful checks, and an error message as string otherwise.} \item{info}{[\code{character(1)}]\cr See \code{\link[testthat]{expect_that}}} \item{label}{[\code{character(1)}]\cr See \code{\link[testthat]{expect_that}}} \item{check.fun}{[\code{function}]\cr Function which checks the input. Must return \code{TRUE} on success and a string with the error message otherwise.} \item{c.fun}{[\code{character(1)}]\cr If not \code{NULL}, instead of calling the function \code{check.fun}, use \code{.Call} to call a C function \dQuote{c.fun} with the identical set of parameters. The C function must be registered as a native symbol, see \code{\link[base]{.Call}}. Useful if \code{check.fun} is just a simple wrapper.} \item{env}{[\code{environment}]\cr The environment of the created function. Default is the \code{\link[base]{parent.frame}}.} } \value{ \code{makeExpectation} invisibly returns the checked object. \code{makeExpectationFunction} returns a \code{function}. } \description{ \code{makeExpectation} is the internal function used to evaluate the result of a check and turn it into an \code{\link[testthat]{expectation}}. \code{makeExceptionFunction} can be used to automatically create an expectation function based on a check function (see example). } \examples{ # Simple custom check function checkFalse = function(x) if (!identical(x, FALSE)) "Must be FALSE" else TRUE # Create the respective expect function expect_false = function(x, info = NULL, label = vname(x)) { res = checkFalse(x) makeExpectation(x, res, info = info, label = label) } # Alternative: Automatically create such a function expect_false = makeExpectationFunction(checkFalse) print(expect_false) } \seealso{ Other CustomConstructors: \code{\link{makeAssertion}}, \code{\link{makeTest}} } checkmate/man/checkDirectoryExists.Rd0000644000176200001440000000635013047277570017422 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkDirectoryExists.R \name{checkDirectoryExists} \alias{checkDirectoryExists} \alias{check_directory_exists} \alias{assertDirectoryExists} \alias{assert_directory_exists} \alias{testDirectoryExists} \alias{test_directory_exists} \alias{expect_directory_exists} \alias{checkDirectory} \alias{assertDirectory} \alias{assert_directory} \alias{testDirectory} \alias{test_directory} \alias{expect_directory} \title{Check for existence and access rights of directories} \usage{ checkDirectoryExists(x, access = "") check_directory_exists(x, access = "") assertDirectoryExists(x, access = "", .var.name = vname(x), add = NULL) assert_directory_exists(x, access = "", .var.name = vname(x), add = NULL) testDirectoryExists(x, access = "") test_directory_exists(x, access = "") expect_directory_exists(x, access = "", info = NULL, label = vname(x)) checkDirectory(x, access = "") assertDirectory(x, access = "", .var.name = vname(x), add = NULL) assert_directory(x, access = "", .var.name = vname(x), add = NULL) testDirectory(x, access = "") test_directory(x, access = "") expect_directory(x, access = "", info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{access}{[\code{character(1)}]\cr Single string containing possible characters \sQuote{r}, \sQuote{w} and \sQuote{x} to force a check for read, write or execute access rights, respectively. Write and executable rights are not checked on Windows.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertDirectoryExists}/\code{assert_directory_exists} return \code{x} invisibly, whereas \code{checkDirectoryExists}/\code{check_directory_exists} and \code{testDirectoryExists}/\code{test_directory_exists} return \code{TRUE}. If the check is not successful, \code{assertDirectoryExists}/\code{assert_directory_exists} throws an error message, \code{testDirectoryExists}/\code{test_directory_exists} returns \code{FALSE}, and \code{checkDirectoryExists} returns a string with the error message. The function \code{expect_directory_exists} always returns an \code{\link[testthat]{expectation}}. } \description{ Check for existence and access rights of directories } \note{ The functions without the suffix \dQuote{exists} are deprecated and will be removed from the package in a future version due to name clashes. } \examples{ # Is R's home directory readable? testDirectory(R.home(), "r") # Is R's home directory readable and writable? testDirectory(R.home(), "rw") } \seealso{ Other filesystem: \code{\link{checkAccess}}, \code{\link{checkFileExists}}, \code{\link{checkPathForOutput}} } checkmate/man/anyInfinite.Rd0000644000176200001440000000105313047277570015530 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/anyInfinite.R \name{anyInfinite} \alias{anyInfinite} \title{Check if an object contains infinite values} \usage{ anyInfinite(x) } \arguments{ \item{x}{[\code{ANY}]\cr Object to check.} } \value{ [\code{logical(1)}] Returns \code{TRUE} if any element is \code{-Inf} or \code{Inf}. } \description{ Supported are atomic types (see \code{\link[base]{is.atomic}}), lists and data frames. } \examples{ anyInfinite(1:10) anyInfinite(c(1:10, Inf)) iris[3, 3] = Inf anyInfinite(iris) } checkmate/man/checkAtomicVector.Rd0000644000176200001440000001105213167637071016647 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkAtomicVector.R \name{checkAtomicVector} \alias{checkAtomicVector} \alias{check_atomic_vector} \alias{assertAtomicVector} \alias{assert_atomic_vector} \alias{testAtomicVector} \alias{test_atomic_vector} \alias{expect_atomic_vector} \title{Check that an argument is an atomic vector} \usage{ checkAtomicVector(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL) check_atomic_vector(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL) assertAtomicVector(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, .var.name = vname(x), add = NULL) assert_atomic_vector(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, .var.name = vname(x), add = NULL) testAtomicVector(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL) test_atomic_vector(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL) expect_atomic_vector(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertAtomicVector}/\code{assert_atomic_vector} return \code{x} invisibly, whereas \code{checkAtomicVector}/\code{check_atomic_vector} and \code{testAtomicVector}/\code{test_atomic_vector} return \code{TRUE}. If the check is not successful, \code{assertAtomicVector}/\code{assert_atomic_vector} throws an error message, \code{testAtomicVector}/\code{test_atomic_vector} returns \code{FALSE}, and \code{checkAtomicVector} returns a string with the error message. The function \code{expect_atomic_vector} always returns an \code{\link[testthat]{expectation}}. } \description{ An atomic vector is defined slightly different from specifications in \code{\link[base]{is.atomic}} and \code{\link[base]{is.vector}}: An atomic vector is either \code{logical}, \code{integer}, \code{numeric}, \code{complex}, \code{character} or \code{raw} and can have any attributes except a dimension attribute (like matrices). I.e., a \code{factor} is an atomic vector, but a matrix or \code{NULL} are not. In short, this is mostly equivalent to \code{is.atomic(x) && !is.null(x) && is.null(dim(x))}. } \examples{ testAtomicVector(letters, min.len = 1L, any.missing = FALSE) } \seealso{ Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} Other atomicvector: \code{\link{checkAtomic}}, \code{\link{checkVector}} } checkmate/man/checkLogical.Rd0000644000176200001440000001070713167637071015630 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkLogical.R \name{checkLogical} \alias{checkLogical} \alias{check_logical} \alias{assertLogical} \alias{assert_logical} \alias{testLogical} \alias{test_logical} \alias{expect_logical} \title{Check if an argument is a vector of type logical} \usage{ checkLogical(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) check_logical(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) assertLogical(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_logical(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testLogical(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) test_logical(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) expect_logical(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertLogical}/\code{assert_logical} return \code{x} invisibly, whereas \code{checkLogical}/\code{check_logical} and \code{testLogical}/\code{test_logical} return \code{TRUE}. If the check is not successful, \code{assertLogical}/\code{assert_logical} throws an error message, \code{testLogical}/\code{test_logical} returns \code{FALSE}, and \code{checkLogical} returns a string with the error message. The function \code{expect_logical} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a vector of type logical } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testLogical(TRUE) testLogical(TRUE, min.len = 1) } \seealso{ \code{\link{checkBit}} Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} } checkmate/man/checkFunction.Rd0000644000176200001440000000700413167637071016037 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkFunction.R \name{checkFunction} \alias{checkFunction} \alias{check_function} \alias{assertFunction} \alias{assert_function} \alias{testFunction} \alias{test_function} \alias{expect_function} \title{Check if an argument is a function} \usage{ checkFunction(x, args = NULL, ordered = FALSE, nargs = NULL, null.ok = FALSE) check_function(x, args = NULL, ordered = FALSE, nargs = NULL, null.ok = FALSE) assertFunction(x, args = NULL, ordered = FALSE, nargs = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_function(x, args = NULL, ordered = FALSE, nargs = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testFunction(x, args = NULL, ordered = FALSE, nargs = NULL, null.ok = FALSE) test_function(x, args = NULL, ordered = FALSE, nargs = NULL, null.ok = FALSE) expect_function(x, args = NULL, ordered = FALSE, nargs = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{args}{[\code{character}]\cr Expected formal arguments. Checks that a function has no arguments if set to \code{character(0)}. Default is \code{NULL} (no check).} \item{ordered}{[\code{logical(1)}]\cr Flag whether the arguments provided in \code{args} must be the first \code{length(args)} arguments of the function in the specified order. Default is \code{FALSE}.} \item{nargs}{[\code{integer(1)}]\cr Required number of arguments, without \code{...}. Default is \code{NULL} (no check).} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertFunction}/\code{assert_function} return \code{x} invisibly, whereas \code{checkFunction}/\code{check_function} and \code{testFunction}/\code{test_function} return \code{TRUE}. If the check is not successful, \code{assertFunction}/\code{assert_function} throws an error message, \code{testFunction}/\code{test_function} returns \code{FALSE}, and \code{checkFunction} returns a string with the error message. The function \code{expect_function} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a function } \examples{ testFunction(mean) testFunction(mean, args = "x") } \seealso{ Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFactor}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} } checkmate/man/AssertCollection.Rd0000644000176200001440000000244113047277570016532 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/AssertCollection.R \name{AssertCollection} \alias{AssertCollection} \alias{makeAssertCollection} \alias{reportAssertions} \title{Collect multiple assertions} \usage{ makeAssertCollection() reportAssertions(collection) } \arguments{ \item{collection}{[\code{AssertCollection}]\cr Object of type \dQuote{AssertCollection} (constructed via \code{makeAssertCollection}).} } \value{ \code{makeAssertCollection()} returns an object of class \dQuote{AssertCollection} and \code{reportCollection} returns invisibly \code{TRUE} if no error is thrown (i.e., no message was collected). } \description{ The function \code{makeAssertCollection()} returns a simple stack-like closure you can pass to all functions of the \code{assert*}-family. All messages get collected and can be reported with \code{reportAssertions()}. Alternatively, you can easily write your own report function or customize the the output of the report function to a certain degree. See the example on how to push custom messages or retrieve all stored messages. } \examples{ x = "a" coll = makeAssertCollection() print(coll$isEmpty()) assertNumeric(x, add = coll) coll$isEmpty() coll$push("Custom error message") coll$getMessages() \dontrun{ reportAssertions(coll) } } checkmate/man/checkTibble.Rd0000644000176200001440000001172413047277570015460 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkTibble.R \name{checkTibble} \alias{checkTibble} \alias{check_tibble} \alias{assertTibble} \alias{assert_tibble} \alias{testTibble} \alias{test_tibble} \alias{expect_tibble} \title{Check if an argument is a tibble} \usage{ checkTibble(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) check_tibble(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) assertTibble(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_tibble(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testTibble(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) test_tibble(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE) expect_tibble(x, types = character(0L), any.missing = TRUE, all.missing = TRUE, min.rows = NULL, min.cols = NULL, nrows = NULL, ncols = NULL, row.names = NULL, col.names = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{types}{[\code{character}]\cr Character vector of class names. Each list element must inherit from at least one of the provided types. The types \dQuote{logical}, \dQuote{integer}, \dQuote{integerish}, \dQuote{double}, \dQuote{numeric}, \dQuote{complex}, \dQuote{character}, \dQuote{factor}, \dQuote{atomic}, \dQuote{vector} \dQuote{atomicvector}, \dQuote{array}, \dQuote{matrix}, \dQuote{list}, \dQuote{function}, \dQuote{environment} and \dQuote{null} are supported. For other types \code{\link[base]{inherits}} is used as a fallback to check \code{x}'s inheritance. Defaults to \code{character(0)} (no check).} \item{any.missing}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are matrices with only missing values allowed? Default is \code{TRUE}.} \item{min.rows}{[\code{integer(1)}]\cr Minimum number of rows.} \item{min.cols}{[\code{integer(1)}]\cr Minimum number of columns.} \item{nrows}{[\code{integer(1)}]\cr Exact number of rows.} \item{ncols}{[\code{integer(1)}]\cr Exact number of columns.} \item{row.names}{[\code{character(1)}]\cr Check for row names. Default is \dQuote{NULL} (no check). See \code{\link{checkNamed}} for possible values. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{col.names}{[\code{character(1)}]\cr Check for column names. Default is \dQuote{NULL} (no check). See \code{\link{checkNamed}} for possible values. Note that you can use \code{\link{checkSubset}} to test for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertTibble}/\code{assert_tibble} return \code{x} invisibly, whereas \code{checkTibble}/\code{check_tibble} and \code{testTibble}/\code{test_tibble} return \code{TRUE}. If the check is not successful, \code{assertTibble}/\code{assert_tibble} throws an error message, \code{testTibble}/\code{test_tibble} returns \code{FALSE}, and \code{checkTibble} returns a string with the error message. The function \code{expect_tibble} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a tibble } \examples{ library(tibble) x = as_tibble(iris) testTibble(x) testTibble(x, nrow = 150, any.missing = FALSE) } \seealso{ Other compound: \code{\link{checkArray}}, \code{\link{checkDataFrame}}, \code{\link{checkDataTable}}, \code{\link{checkMatrix}} } checkmate/man/wf.Rd0000644000176200001440000000140413047277570013667 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/wfwl.R \name{wf} \alias{wf} \alias{wl} \title{Get the index of the first/last TRUE} \usage{ wf(x, use.names = TRUE) wl(x, use.names = TRUE) } \arguments{ \item{x}{[\code{logical}]\cr Logical vector.} \item{use.names}{[\code{logical(1)}]\cr If \code{TRUE} and \code{x} is named, the result is also named.} } \value{ [\code{integer(1)} | \code{integer(0)}]. Returns the index of the first/last \code{TRUE} value in \code{x} or an empty integer vector if none is found. NAs are ignored. } \description{ A quick C implementation for \dQuote{which.first} (\code{head(which(x), 1)}) and \dQuote{which.last} (\code{tail(which(x), 1)}). } \examples{ wf(c(FALSE, TRUE)) wl(c(FALSE, FALSE)) wf(NA) } checkmate/man/checkAccess.Rd0000644000176200001440000000453613047277570015463 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkAccess.R \name{checkAccess} \alias{checkAccess} \alias{check_access} \alias{assertAccess} \alias{assert_access} \alias{testAccess} \alias{test_access} \alias{expect_access} \title{Check file system access rights} \usage{ checkAccess(x, access = "") check_access(x, access = "") assertAccess(x, access = "", .var.name = vname(x), add = NULL) assert_access(x, access = "", .var.name = vname(x), add = NULL) testAccess(x, access = "") test_access(x, access = "") expect_access(x, access = "", info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{access}{[\code{character(1)}]\cr Single string containing possible characters \sQuote{r}, \sQuote{w} and \sQuote{x} to force a check for read, write or execute access rights, respectively. Write and executable rights are not checked on Windows.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertAccess}/\code{assert_access} return \code{x} invisibly, whereas \code{checkAccess}/\code{check_access} and \code{testAccess}/\code{test_access} return \code{TRUE}. If the check is not successful, \code{assertAccess}/\code{assert_access} throws an error message, \code{testAccess}/\code{test_access} returns \code{FALSE}, and \code{checkAccess} returns a string with the error message. The function \code{expect_access} always returns an \code{\link[testthat]{expectation}}. } \description{ Check file system access rights } \examples{ # Is R's home directory readable? testAccess(R.home(), "r") # Is R's home directory writeable? testAccess(R.home(), "w") } \seealso{ Other filesystem: \code{\link{checkDirectoryExists}}, \code{\link{checkFileExists}}, \code{\link{checkPathForOutput}} } checkmate/man/asInteger.Rd0000644000176200001440000000545313064452167015200 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/asInteger.R \name{asInteger} \alias{asInteger} \alias{asCount} \alias{asInt} \title{Convert an argument to an integer} \usage{ asInteger(x, tol = sqrt(.Machine$double.eps), lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, .var.name = vname(x)) asCount(x, na.ok = FALSE, positive = FALSE, tol = sqrt(.Machine$double.eps), .var.name = vname(x)) asInt(x, na.ok = FALSE, lower = -Inf, upper = Inf, tol = sqrt(.Machine$double.eps), .var.name = vname(x)) } \arguments{ \item{x}{[any]\cr Object to convert.} \item{tol}{[\code{double(1)}]\cr Numerical tolerance used to check whether a double or complex can be converted. Default is \code{sqrt(.Machine$double.eps)}.} \item{lower}{[\code{numeric(1)}]\cr Lower value all elements of \code{x} must be greater than.} \item{upper}{[\code{numeric(1)}]\cr Upper value all elements of \code{x} must be lower than.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{sorted}{[\code{logical(1)}]\cr Elements must be sorted in ascending order. Missing values are ignored.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in error messages. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{na.ok}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{FALSE}.} \item{positive}{[\code{logical(1)}]\cr Must \code{x} be positive (>= 1)? Default is \code{FALSE}.} } \value{ Converted \code{x}. } \description{ \code{asInteger} is intended to be used for vectors while \code{asInt} is a specialization for scalar integers and \code{asCount} for scalar non-negative integers. Convertible are (a) atomic vectors with all elements \code{NA} and (b) double vectors with all elements being within \code{tol} range of an integer. } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ asInteger(c(1, 2, 3)) asCount(1) asInt(1) } checkmate/man/checkFileExists.Rd0000644000176200001440000000665013047277570016340 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkFileExists.R \name{checkFileExists} \alias{checkFileExists} \alias{check_file_exists} \alias{assertFileExists} \alias{assert_file_exists} \alias{testFileExists} \alias{test_file_exists} \alias{expect_file_exists} \alias{checkFile} \alias{assertFile} \alias{assert_file} \alias{testFile} \alias{expect_file} \title{Check existence and access rights of files} \usage{ checkFileExists(x, access = "", extension = NULL) check_file_exists(x, access = "", extension = NULL) assertFileExists(x, access = "", extension = NULL, .var.name = vname(x), add = NULL) assert_file_exists(x, access = "", extension = NULL, .var.name = vname(x), add = NULL) testFileExists(x, access = "", extension = NULL) test_file_exists(x, access = "", extension = NULL) expect_file_exists(x, access = "", extension = NULL, info = NULL, label = vname(x)) checkFile(x, access = "", extension = NULL) assertFile(x, access = "", extension = NULL, .var.name = vname(x), add = NULL) assert_file(x, access = "", extension = NULL, .var.name = vname(x), add = NULL) testFile(x, access = "", extension = NULL) expect_file(x, access = "", extension = NULL, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{access}{[\code{character(1)}]\cr Single string containing possible characters \sQuote{r}, \sQuote{w} and \sQuote{x} to force a check for read, write or execute access rights, respectively. Write and executable rights are not checked on Windows.} \item{extension}{[\code{character}]\cr Vector of allowed file extensions, matched case insensitive.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertFileExists}/\code{assert_file_exists} return \code{x} invisibly, whereas \code{checkFileExists}/\code{check_file_exists} and \code{testFileExists}/\code{test_file_exists} return \code{TRUE}. If the check is not successful, \code{assertFileExists}/\code{assert_file_exists} throws an error message, \code{testFileExists}/\code{test_file_exists} returns \code{FALSE}, and \code{checkFileExists} returns a string with the error message. The function \code{expect_file_exists} always returns an \code{\link[testthat]{expectation}}. } \description{ Check existence and access rights of files } \note{ The functions without the suffix \dQuote{exists} are deprecated and will be removed from the package in a future version due to name clashes. \code{test_file} has been unexported already. } \examples{ # Check if R's COPYING file is readable testFileExists(file.path(R.home(), "COPYING"), access = "r") # Check if R's COPYING file is readable and writable testFileExists(file.path(R.home(), "COPYING"), access = "rw") } \seealso{ Other filesystem: \code{\link{checkAccess}}, \code{\link{checkDirectoryExists}}, \code{\link{checkPathForOutput}} } checkmate/man/checkFactor.Rd0000644000176200001440000001334413167637071015474 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkFactor.R \name{checkFactor} \alias{checkFactor} \alias{check_factor} \alias{assertFactor} \alias{assert_factor} \alias{testFactor} \alias{test_factor} \alias{expect_factor} \title{Check if an argument is a factor} \usage{ checkFactor(x, levels = NULL, ordered = NA, empty.levels.ok = TRUE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, n.levels = NULL, min.levels = NULL, max.levels = NULL, unique = FALSE, names = NULL, null.ok = FALSE) check_factor(x, levels = NULL, ordered = NA, empty.levels.ok = TRUE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, n.levels = NULL, min.levels = NULL, max.levels = NULL, unique = FALSE, names = NULL, null.ok = FALSE) assertFactor(x, levels = NULL, ordered = NA, empty.levels.ok = TRUE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, n.levels = NULL, min.levels = NULL, max.levels = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_factor(x, levels = NULL, ordered = NA, empty.levels.ok = TRUE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, n.levels = NULL, min.levels = NULL, max.levels = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL) testFactor(x, levels = NULL, ordered = NA, empty.levels.ok = TRUE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, n.levels = NULL, min.levels = NULL, max.levels = NULL, unique = FALSE, names = NULL, null.ok = FALSE) test_factor(x, levels = NULL, ordered = NA, empty.levels.ok = TRUE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, n.levels = NULL, min.levels = NULL, max.levels = NULL, unique = FALSE, names = NULL, null.ok = FALSE) expect_factor(x, levels = NULL, ordered = NA, empty.levels.ok = TRUE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, n.levels = NULL, min.levels = NULL, max.levels = NULL, unique = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{levels}{[\code{character}]\cr Vector of allowed factor levels.} \item{ordered}{[\code{logical(1)}]\cr Check for an ordered factor? If \code{FALSE} or \code{TRUE}, checks explicitly for an unordered or ordered factor, respectively. Default is \code{NA} which does not perform any additional check.} \item{empty.levels.ok}{[\code{logical(1)}]\cr Are empty levels allowed? Default is \code{TRUE}.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{n.levels}{[\code{integer(1)}]\cr Exact number of factor levels. Default is \code{NULL} (no check).} \item{min.levels}{[\code{integer(1)}]\cr Minimum number of factor levels. Default is \code{NULL} (no check).} \item{max.levels}{[\code{integer(1)}]\cr Maximum number of factor levels. Default is \code{NULL} (no check).} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertFactor}/\code{assert_factor} return \code{x} invisibly, whereas \code{checkFactor}/\code{check_factor} and \code{testFactor}/\code{test_factor} return \code{TRUE}. If the check is not successful, \code{assertFactor}/\code{assert_factor} throws an error message, \code{testFactor}/\code{test_factor} returns \code{FALSE}, and \code{checkFactor} returns a string with the error message. The function \code{expect_factor} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a factor } \examples{ x = factor("a", levels = c("a", "b")) testFactor(x) testFactor(x, empty.levels.ok = FALSE) } \seealso{ Other basetypes: \code{\link{checkArray}}, \code{\link{checkAtomicVector}}, \code{\link{checkAtomic}}, \code{\link{checkCharacter}}, \code{\link{checkComplex}}, \code{\link{checkDataFrame}}, \code{\link{checkDate}}, \code{\link{checkEnvironment}}, \code{\link{checkFunction}}, \code{\link{checkIntegerish}}, \code{\link{checkInteger}}, \code{\link{checkList}}, \code{\link{checkLogical}}, \code{\link{checkMatrix}}, \code{\link{checkNull}}, \code{\link{checkNumeric}}, \code{\link{checkPOSIXct}}, \code{\link{checkVector}} } checkmate/man/checkNamed.Rd0000644000176200001440000000427013047277570015301 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkNamed.R \name{checkNamed} \alias{checkNamed} \alias{check_named} \alias{assertNamed} \alias{assert_named} \alias{testNamed} \alias{test_named} \title{Check if an argument is named} \usage{ checkNamed(x, type = "named") check_named(x, type = "named") assertNamed(x, type = "named", .var.name = vname(x), add = NULL) assert_named(x, type = "named", .var.name = vname(x), add = NULL) testNamed(x, type = "named") test_named(x, type = "named") } \arguments{ \item{x}{[any]\cr Object to check.} \item{type}{[character(1)]\cr Select the check(s) to perform. \dQuote{unnamed} checks \code{x} to be unnamed. \dQuote{named} (default) checks \code{x} to be named which excludes names to be \code{NA} or empty (\code{""}). \dQuote{unique} additionally tests for non-duplicated names. \dQuote{strict} checks for unique names which comply to R's variable name restrictions. Note that for zero-length \code{x} every name check evaluates to \code{TRUE}.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertNamed}/\code{assert_named} return \code{x} invisibly, whereas \code{checkNamed}/\code{check_named} and \code{testNamed}/\code{test_named} return \code{TRUE}. If the check is not successful, \code{assertNamed}/\code{assert_named} throws an error message, \code{testNamed}/\code{test_named} returns \code{FALSE}, and \code{checkNamed} returns a string with the error message. The function \code{expect_named} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is named } \note{ These function are deprecated and will be removed in a future version. Please use \code{\link{checkNames}} instead. } \examples{ x = 1:3 testNamed(x, "unnamed") names(x) = letters[1:3] testNamed(x, "unique") } \seealso{ Other attributes: \code{\link{checkClass}}, \code{\link{checkNames}} } checkmate/LICENSE0000644000176200001440000000005113117514102013172 0ustar liggesusersYEAR: 2017 COPYRIGHT HOLDER: Michel Lang