checkmate/0000755000176200001440000000000014651705516012210 5ustar liggesuserscheckmate/tests/0000755000176200001440000000000014245411067013344 5ustar liggesuserscheckmate/tests/testthat/0000755000176200001440000000000014646750427015217 5ustar liggesuserscheckmate/tests/testthat/test_interoperability.R0000644000176200001440000000160114646134572021761 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, nrows = 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, nrows = 150, min.cols = 2, any.missing = FALSE, col.names = "strict")) expect_true(testDataFrame(tibble())) }) 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_checkNames.R0000644000176200001440000001210014245411067020421 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("\u00e4", type = "strict")) expect_false(testNames("\u00e4", type = "ids")) expect_error(assertNames(c("a", "a"), "unique"), "unique") expect_error(assertNames(c("a", "a"), "strict"), "unique") expect_true(testNames(c("a", "a"), "ids")) 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)) expect_error( assert_names(names(x), subset.of = c("a", "b")), "{'c'}", fixed = TRUE ) }) 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)) expect_error( assert_names(names(x), identical.to = c("a", "b")), "{'a','b','c'}", fixed = TRUE ) }) 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)) expect_error( assert_names(names(x), permutation.of = c("a", "b")), "{'c'}", fixed = TRUE ) expect_error( assert_names(names(x), permutation.of = c("a", "b", "c", "d")), "{'d'}", fixed = TRUE ) }) 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)) expect_error( assert_names(names(x), must.include = c("a", "b", "c", "d")), "{'d'}", fixed = TRUE ) }) test_that("checkNames / disjunct.from", { x = 1:3 names(x) = letters[1:3] expect_true(testNames(names(x))) expect_true(testNames(names(x), disjunct.from = "d")) expect_false(testNames(names(x), disjunct.from = "b")) expect_error( assert_names(names(x), disjunct.from = c("c")), "{'c'}", fixed = TRUE ) }) 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_asType.R0000644000176200001440000000454114245411067017637 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_checkNumeric.R0000644000176200001440000000652214645726235021005 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)) } ## see https://github.com/mllg/checkmate/issues/258 expect_true(grepl("sorted", checkNumeric(c(3, NA, 2), sorted = TRUE), fixed = TRUE)) }) test_that("names check works", { expect_true(grepl("names", check_numeric(0:1, names = "unique"))) }) test_that("typed.missing", { expect_true(testNumeric(NA)) expect_true(testNumeric(NA, typed.missing = FALSE)) expect_false(testNumeric(NA, typed.missing = TRUE)) expect_true(testNumeric(character())) expect_true(testNumeric(character(), typed.missing = FALSE)) expect_false(testNumeric(character(), typed.missing = TRUE)) }) test_that("Inf bound checks", { expect_false(testNumeric(2, lower = Inf)) expect_true(testNumeric(2, lower = -Inf)) expect_true(testNumeric(2, upper = Inf)) expect_false(testNumeric(2, upper = -Inf)) }) checkmate/tests/testthat/test_altreps.R0000644000176200001440000000206114245411067020037 0ustar liggesuserscontext("ALTREPS") test_that("ALTREP no na", { skip_if(getRversion() < "3.5.0") wrapper = function(x, srt = 0, nna = 0) .Internal(wrap_meta(x, srt, nna)) x = c(1, NA, 3) xw = wrapper(x, nna = 1) expect_true(anyMissing(x)) expect_false(anyMissing(xw)) x = as.integer(c(1, NA, 3)) xw = wrapper(x, nna = 1) expect_true(anyMissing(x)) expect_false(anyMissing(xw)) x = c("a", NA, "b") xw = wrapper(x, nna = 1) expect_true(anyMissing(x)) expect_false(anyMissing(xw)) }) test_that("ALTREP sorted", { skip_if(getRversion() < "3.5.0") wrapper = function(x, srt = 0, nna = 0) .Internal(wrap_meta(x, srt, nna)) x = c(3, 1, 2) xw = wrapper(x, srt = 1) expect_false(testNumeric(x, sorted = TRUE)) expect_true(testNumeric(xw, sorted = TRUE)) x = as.integer(c(3, 1, 2)) xw = wrapper(x, srt = 1) expect_false(testInteger(x, sorted = TRUE)) expect_true(testInteger(xw, sorted = TRUE)) x = c("c", "a", "b") xw = wrapper(x, srt = 1) expect_false(testCharacter(x, sorted = TRUE)) expect_true(testCharacter(xw, sorted = TRUE)) }) checkmate/tests/testthat/test_checkAtomic.R0000644000176200001440000000301314531605563020601 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") # handling of is.null for future versions of R, see # https://stat.ethz.ch/pipermail/r-devel/2023-September/082892.html expect_equal(vlapply(li, function(x) is.atomic(x) || is.null(x)), vlapply(li, testAtomic)) }) checkmate/tests/testthat/test_checkCount.R0000644000176200001440000000147014264222022020446 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_false(is.integer(assertCount(5))) expect_true(is.integer(assertCount(5, coerce = TRUE))) expect_error(assertCount(-1), ">= 0") }) checkmate/tests/testthat/test_checkVector.R0000644000176200001440000000461214245411067020631 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_checkSubset.R0000644000176200001440000000305414646134572020643 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", { skip_if_not_installed("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") }) test_that("checkSubset / NAs (#158)", { expect_true(test_subset(NA_character_, NA)) expect_true(test_subset(NA, NA_character_)) }) checkmate/tests/testthat/test_checkMultiClass.R0000644000176200001440000000063314245411067021446 0ustar liggesuserscontext("checkMultiClass") test_that("checkMultiClass", { myobj = 1 expect_succ_all(MultiClass, myobj, "numeric", cc = "MultiClass", lc = "multi_class") expect_fail_all(MultiClass, myobj, "integer") foo = 1 class(foo) = c("a", "b") expect_true(testMultiClass(foo, "a")) expect_true(testMultiClass(foo, "b")) expect_false(testClass(foo, "c")) expect_true(testMultiClass(foo, c("c", "b"))) }) checkmate/tests/testthat/test_checkDataFrame.R0000644000176200001440000001071014245411067021207 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"), "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)) expect_true(testDataFrame(x, max.rows = 200L)) expect_false(testDataFrame(x, max.rows = 100L)) expect_true(testDataFrame(x, max.cols = 10L)) expect_false(testDataFrame(x, max.cols = 2L)) }) 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"), "colnames") names(df) = c("x", "") expect_error(assertDataFrame(df, col.names = "named"), "empty") names(df) = c("x", "x") expect_identical(assertDataFrame(df, col.names = "named"), df) expect_error(assertDataFrame(df, col.names = "unique"), "duplicated") expect_error(assertDataFrame(df, col.names = "strict"), "duplicated") expect_error(assertDataFrame(df, col.names = "foo"), "type") 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, max.rows = 200)) expect_false(testDataFrame(x, max.rows = 100)) 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, max.cols = 5)) expect_false(testDataFrame(x, max.cols = 2)) 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$a[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)) }) test_that("missing locations are reported correctly", { x = data.frame(a = 1:2, b = 1:2); x$a[1] = NA expect_true(grepl("column 'a', row 1", checkDataFrame(x, any.missing = FALSE))) x = data.frame(a = 1:2, b = 1:2); x$b[1] = NA expect_true(grepl("column 'b', row 1", checkDataFrame(x, any.missing = FALSE))) x = data.frame(a = 1:2, b = 1:2); x$b[2] = NA expect_true(grepl("column 'b', row 2", checkDataFrame(x, any.missing = FALSE))) x = data.frame(a = 1:2, b = 1:2, c = 1:2); x$c[2] = NA expect_true(grepl("column 'c', row 2", checkDataFrame(x, any.missing = FALSE))) }) checkmate/tests/testthat/test_matchArg.R0000644000176200001440000000121314245411067020111 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_checkPermutation.R0000644000176200001440000000301714421735677021710 0ustar liggesuserscontext("checkPermutation") test_that("checkPermutation", { expect_false(testPermutation(1L, c(1L, 2L))) expect_true(testPermutation(2:1, 1:2)) expect_false(testPermutation(1, c(1, 2))) expect_true(testPermutation(c(2, 1), c(1, 2))) expect_true(testPermutation(letters[1:2], letters[2:1])) expect_false(testPermutation(letters[c(1, 1, 2)], letters[1:2])) expect_true(testPermutation(as.factor(letters[1:2]), as.factor(letters[2:1]))) expect_false(testPermutation(as.factor(letters[c(1, 1, 2)]), as.factor(letters[1:2]))) expect_true(testPermutation(as.ordered(letters[1:2]), as.ordered(letters[2:1]))) expect_false(testPermutation(as.ordered(letters[c(1, 1, 2)]), as.ordered(letters[1:2]))) expect_true(testPermutation(c(1 + 2i, 1), c(1, 1 + 2i))) expect_false(testPermutation(c(1 + 2i, 1 + 3i), c(1, 1 + 2i))) expect_true(testPermutation(c(FALSE, TRUE, NA), c(NA, TRUE, FALSE))) expect_false(testPermutation(c(FALSE, TRUE, NA, NA), c(NA, TRUE, FALSE))) expect_true(testPermutation(c(NA, 1), c(1, NA))) expect_false(testPermutation(c(1, 1, 1), c(1))) expect_true(testPermutation(1, 1L)) expect_false(testPermutation(c(1, 1, 2), c(2, 2, 1))) expect_false(testPermutation(c("a", NA, "b", "b", NA), c(NA, NA, "a", "b", "a"))) expect_true(testPermutation(c("a", NA, "b", "b", NA), c(NA, NA, "b", "b", "a"))) expect_false(testPermutation(c("a", NA, "b", "b"), c(NA, NA, "b", "b", "a"))) expect_false(testPermutation(c(1, NA), c(NA, 1), na.ok = FALSE)) expect_false(testPermutation(c(1, NA), c(1))) }) checkmate/tests/testthat/test_checkDouble.R0000644000176200001440000000550214245411067020600 0ustar liggesuserscontext("checkDouble") test_that("checkDouble", { myobj = 1 expect_succ_all(Double, myobj) myobj = "a" expect_fail_all(Double, myobj) expect_true(testDouble(integer(0))) expect_false(testDouble(NULL)) expect_false(testDouble(TRUE)) expect_false(testDouble(FALSE)) expect_true(testDouble(NA_character_)) expect_true(testDouble(NA_real_)) expect_true(testDouble(NaN)) expect_false(testDouble(NA_real_, any.missing = FALSE)) expect_false(testDouble(NA_real_, all.missing = FALSE)) expect_false(testDouble(NaN, any.missing = FALSE)) expect_false(testDouble(NaN, all.missing = FALSE)) expect_false(testDouble(1L)) expect_true(testDouble(1)) expect_true(testDouble(Inf)) expect_true(testDouble(-Inf)) expect_identical(assertDouble(1:2 + 0.1, finite = TRUE), 1:2 + 0.1) expect_error(assertDouble(c(1, Inf), finite = TRUE), "finite") expect_error(assertDouble(c(1, -Inf), finite = TRUE), "finite") expect_true(testDouble(1:3 + 0.1, any.missing=FALSE, min.len=1L, max.len=3L)) expect_false(testDouble(1:3 + 0.1, any.missing=FALSE, len=5)) expect_true(testDouble(1:3 + 0.1, lower = 1L, upper = 3.5)) expect_false(testDouble(1:3 + 0.1, lower = 5)) expect_error(assertDouble("a"), "double") }) test_that("bounds are checked", { expect_error(checkDouble(1, lower = "a"), "number") expect_error(checkDouble(1, lower = 1:2), "length") expect_error(checkDouble(1, lower = NA_real_), "missing") expect_error(checkDouble(1, upper = "a"), "number") expect_error(checkDouble(1, upper = 1:2), "length") expect_error(checkDouble(1, upper = NA_real_), "missing") }) test_that("bounds of vectors with only missings are not checked", { expect_true(checkDouble(NA, lower = 1)) expect_true(checkDouble(NA_character_, upper = 10)) }) test_that("sorted works", { xu = runif(10) while(!is.unsorted(xu)) xu = runif(10) xs = sort(xu) expect_true(checkDouble(xs, sorted = TRUE)) expect_true(grepl("sorted", checkDouble(xu, sorted = TRUE), fixed = TRUE)) expect_true(checkDouble(1., sorted = TRUE)) expect_true(checkDouble(double(0), sorted = TRUE)) expect_true(checkDouble(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", checkDouble(xu, sorted = TRUE), fixed = TRUE)) else expect_true(grepl("sorted", checkDouble(xu, sorted = TRUE), fixed = TRUE)) } }) test_that("typed.missing", { expect_true(testDouble(NA_character_)) expect_true(testDouble(NA_character_, typed.missing = FALSE)) expect_false(testDouble(NA_character_, typed.missing = TRUE)) expect_true(testDouble(character())) expect_true(testDouble(character(), typed.missing = FALSE)) expect_false(testDouble(character(), typed.missing = TRUE)) }) checkmate/tests/testthat/test_checkScalar.R0000644000176200001440000000076114245411067020575 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_checkInteger.R0000644000176200001440000000436014245411067020764 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)) } }) test_that("factors are detected (#164)", { x = factor(letters) expect_error(assertInteger(x), "factor") }) test_that("typed.missing", { expect_true(testInteger(NA_character_)) expect_true(testInteger(NA_character_, typed.missing = FALSE)) expect_false(testInteger(NA_character_, typed.missing = TRUE)) expect_true(testInteger(character())) expect_true(testInteger(character(), typed.missing = FALSE)) expect_false(testInteger(character(), typed.missing = TRUE)) }) checkmate/tests/testthat/teardown.R0000644000176200001440000000006614245411067017154 0ustar liggesusersif (getRversion() >= "3.6.0") { options(old_opts) } checkmate/tests/testthat/test_messages.R0000644000176200001440000000132414245411067020175 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'\\.$") }) test_that("Correct frame is reported by assertions", { f1a <- function(num) if(!is.numeric(num)) stop("Not numeric") f1b <- function(num) assert_numeric(num) f2a <- function(num) f1a(num) f2b <- function(num) f1b(num) ok.r = try(f2a(letters), silent = TRUE) ok.cm = try(f2b(letters), silent = TRUE) expect_true(grepl("f1a(num)", as.character(ok.r), fixed = TRUE)) expect_true(grepl("f1b(num)", as.character(ok.cm), fixed = TRUE)) }) checkmate/tests/testthat/test_deparse.R0000644000176200001440000000034214245411067020010 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/testthat/test_checkSetEqual.R0000644000176200001440000000362414646134572021124 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", { skip_if_not_installed("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") }) test_that("checkSetEqual / NAs (#158)", { expect_true(test_set_equal(NA_character_, NA)) expect_true(test_set_equal(NA, NA_character_)) }) checkmate/tests/testthat/test_checkDisjunct.R0000644000176200001440000000230114646134572021153 0ustar liggesuserscontext("checkDisjunct") test_that("checkDisjunct", { myobj = 1:3 expect_succ_all(Disjunct, myobj, letters) myobj = "b" expect_fail_all(Disjunct, myobj, letters) expect_true(testDisjunct(character(0), letters)) expect_true(testDisjunct(letters, character(0))) expect_true(testDisjunct(character(0L), character(0))) expect_false(testDisjunct(factor("a"), letters)) expect_false(testDisjunct(1., 1:2)) expect_false(testDisjunct(factor("a"), factor(letters))) expect_true(testDisjunct(NA_integer_, 1:10)) expect_false(testDisjunct(NA_integer_, c(1:10, NA_integer_))) expect_error(assertSubset(1L, list()), "atomic") expect_true(testDisjunct(integer(0), character(0))) expect_error(assert_disjunct("a", "a"), "disjunct from") }) test_that("checkSubset / fastmatch", { skip_if_not_installed("fastmatch") x = "c" y = letters[1:5] res = testDisjunct(x, y) expect_false(res) expect_null(attr(y, ".match.hash")) res = testDisjunct(x, y, fmatch = TRUE) expect_false(res) expect_class(attr(y, ".match.hash"), "match.hash") }) test_that("checkDisjunct / NAs (#158)", { expect_false(test_disjunct(NA_character_, NA)) expect_false(test_disjunct(NA, NA_character_)) }) checkmate/tests/testthat/test_checkOS.R0000644000176200001440000000015514245411067017706 0ustar liggesuserscontext("checkOS") test_that("checkOS", { expect_succ_all(OS, c("linux", "mac", "windows", "solaris")) }) checkmate/tests/testthat/test_include.R0000644000176200001440000000064614245411067020017 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_makeFunction.R0000644000176200001440000000446514245411067021022 0ustar liggesuserscontext("makeXFunction") test_that("makeAssertion", { x = assertFlag y = makeAssertionFunction(checkFlag, c.fun = "c_check_flag", use.namespace = FALSE) expect_identical(formals(x), formals(y)) if (!isNamespaceLoaded("covr")) expect_equal(body(x), body(y)) x = assertList y = makeAssertionFunction(checkList, use.namespace = FALSE) expect_identical(formals(x), formals(y)) if (!isNamespaceLoaded("covr")) 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)) if (!isNamespaceLoaded("covr")) expect_equal(body(x), body(y)) x = testList y = makeTestFunction(checkList) expect_identical(formals(x), formals(y)) if (!isNamespaceLoaded("covr")) 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", use.namespace = FALSE) expect_identical(formals(x), formals(y)) if (!isNamespaceLoaded("covr")) expect_equal(body(x), body(y)) x = expect_list y = makeExpectationFunction(checkList, use.namespace = FALSE) expect_identical(formals(x), formals(y)) if (!isNamespaceLoaded("covr")) expect_equal(body(x), body(y)) }) test_that("makeX with name for 'x' not 'x'", { checker = function(foo, bar = TRUE) check_numeric(foo) achecker = makeAssertionFunction(checker) expect_identical(names(formals(achecker)), c("foo", "bar", ".var.name", "add")) expect_identical(as.character(formals(achecker)$.var.name)[2], "foo") expect_equal(sum(grepl("foo", as.character(body(achecker)))), 3L) expect_equal(sum(grepl("bar", as.character(body(achecker)))), 1L) tchecker = makeTestFunction(checker) expect_identical(names(formals(tchecker)), c("foo", "bar")) expect_equal(sum(grepl("foo", as.character(body(tchecker)))), 1L) expect_equal(sum(grepl("bar", as.character(body(tchecker)))), 1L) echecker = makeExpectationFunction(checker) expect_identical(names(formals(echecker)), c("foo", "bar", "info", "label")) expect_equal(sum(grepl("foo", as.character(body(echecker)))), 3L) expect_equal(sum(grepl("bar", as.character(body(echecker)))), 1L) }) checkmate/tests/testthat/test_checkNumber.R0000644000176200001440000000212614245411067020615 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_checkFlag.R0000644000176200001440000000073014245411067020235 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_AssertCollection.R0000644000176200001440000000212614245411067021644 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_guessType.R0000644000176200001440000000262314245411067020361 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_checkString.R0000644000176200001440000000256514646750427020655 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)) expect_true(testString("a", n.chars = 1)) expect_false(testString("", n.chars = 1)) expect_true(testString("a", max.chars = 1)) expect_false(testString("ab", max.chars = 1)) }) checkmate/tests/testthat/test_checkFALSE.R0000644000176200001440000000027414245411067020221 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/helper.R0000644000176200001440000000636314245411067016616 0ustar liggesuserslibrary(testthat) expect_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(args(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 = get0(s, envir = asNamespace("checkmate"), inherits = FALSE) if (!is.null(fun)) 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(args(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 = get0(s, envir = asNamespace("checkmate"), inherits = FALSE) if (!is.null(fun)) { 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_checkIntegerish.R0000644000176200001440000000716714263526765021514 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") expect_false(is.integer(assertIntegerish(5))) expect_true(is.integer(assertIntegerish(5, coerce = TRUE))) }) 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)) }) test_that("informative error messages", { x = checkIntegerish((.Machine$integer.max + as.double(-3:3))) expect_string(x, fixed = "element 5") expect_string(x, fixed = "integer range") x = checkIntegerish((-.Machine$integer.max - 1)) expect_string(x, fixed = "element 1") expect_string(x, fixed = "integer range") x = checkIntegerish(0.5) expect_string(x, fixed = "close to an integer") x = checkIntegerish(3 + 1i) expect_string(x, fixed = "imaginary part") }) test_that("factors are detected (#164)", { x = factor(letters) expect_error(assertIntegerish(x), "factor") }) test_that("Dates are detected (#223)", { x = Sys.Date() expect_error(assertIntegerish(x), "Date") }) test_that("POSIXt is detected (#223)", { x = Sys.time() expect_error(assertIntegerish(x), "POSIX") }) test_that("0 tolerance works (#177)", { expect_true(isIntegerish(1, tol = 0)) }) test_that("coerce rounds to next integer", { x = 1 - sqrt(.Machine$double.eps) / 10 y = assert_integerish(x, coerce = TRUE) expect_identical(y, 1L) }) test_that("typed.missing", { expect_true(testIntegerish(NA_character_)) expect_true(testIntegerish(NA_character_, typed.missing = FALSE)) expect_false(testIntegerish(NA_character_, typed.missing = TRUE)) expect_true(testIntegerish(character())) expect_true(testIntegerish(character(), typed.missing = FALSE)) expect_false(testIntegerish(character(), typed.missing = TRUE)) }) test_that("#226", { expect_true(test_integerish(NA_character_, any.missing = TRUE, all.missing = TRUE)) }) checkmate/tests/testthat/test_checkDate.R0000644000176200001440000000640514245411067020246 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_checkFormula.R0000644000176200001440000000050214245411067020766 0ustar liggesuserscontext("checkFormula") test_that("checkFormula", { f = ~ x expect_succ_all(Formula, f) expect_fail_all(Formula, 1) f = y ~ x + z expect_true(checkFormula(f)) f = y ~ x:z + I(a) expect_true(checkFormula(f)) expect_true(checkFormula(NULL, null.ok = TRUE)) expect_error(assertFormula(1, "formula")) }) checkmate/tests/testthat/test_assert.R0000644000176200001440000000462214245411067017673 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) }) test_that("correct variable is reported (#182)", { f = function(a, b) assert(checkFunction(a), checkNumeric(b), combine = "and") expect_error(f(identity, "a"), "'b'") }) test_that("can push to collection", { coll = makeAssertCollection() x = NULL expect_error(assert(checkNull(x), .var.name = c("a", "b"), add = coll), "length") expect_error(assert(checkNull(x), add = "not_assert_coll"), "AssertCollection") expect_true(assert(checkNull(x), add = coll)) expect_true(coll$isEmpty()) expect_true(assert(checkNull(x), checkDataFrame(x), add = coll)) expect_true(coll$isEmpty()) grepme = iris expect_true(assert(checkNull(grepme), checkDataFrame(grepme), add = coll)) expect_true(coll$isEmpty()) assert(checkNull(grepme), checkNumeric(grepme), add = coll) expect_match( coll$getMessages(), "Variable.+One of") assert(checkNull(grepme), checkNumeric(x), add = coll) expect_match( coll$getMessages()[2], "Variables.+grepme.+x.+One of") assert( checkNull(grepme), checkNumeric(x), .var.name = "TEST", add = coll) expect_match( coll$getMessages()[3], "Variable.+TEST.+One of") assert( checkNull(grepme), checkNumeric(x), .var.name = c("V1", "V2"), add = coll) expect_match( coll$getMessages()[4], "Variable.+V1.+V2.+One of") })checkmate/tests/testthat/test_checkArray.R0000644000176200001440000000275414245411067020452 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_checkFactor.R0000644000176200001440000000360714245411067020610 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") }) test_that("typed.missing", { expect_false(testFactor(NA)) expect_false(testFactor(NA_integer_)) expect_true(testFactor(factor(levels = "a"))) expect_false(testFactor(character(0))) }) checkmate/tests/testthat/test_checkFunction.R0000644000176200001440000000407214421476677021172 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") }) test_that("checkFunction with Primitives", { expect_true(testFunction(sqrt)) expect_true(testFunction(sqrt, args = "x")) expect_true(testFunction(as.logical, nargs = 1)) # bug 144 }) test_that("ordered and no args (#204)", { f = function() 0 expect_error(assertFunction(f, args = c("a", "b"), ordered = FALSE), "formal arguments") expect_error(assertFunction(f, args = c("a", "b"), ordered = TRUE), "formal arguments") }) checkmate/tests/testthat/test_checkRaw.R0000644000176200001440000000103414245411067020113 0ustar liggesuserscontext("checkRaw") test_that("checkRaw", { myobj = as.raw(1) expect_succ_all(Raw, myobj) myobj = 1 expect_fail_all(Raw, myobj) expect_true(testRaw(as.raw(NULL))) expect_false(testRaw(NULL)) expect_true(testRaw(as.raw(NULL), len = 0)) expect_true(testRaw(as.raw(1), len = 1)) expect_true(testRaw(as.raw(1), min.len = 1, max.len = 1)) x = as.raw(1:2) names(x) = letters[1:2] expect_true(testRaw(x, names = "unique")) expect_error(assertRaw(1), "raw") expect_error(assertRaw(as.raw(1), len = 2), "length") }) checkmate/tests/testthat/test_anyInfinite.R0000644000176200001440000000141114245411067020640 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_checkLogical.R0000644000176200001440000000171114245411067020736 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") }) test_that("typed.missing", { expect_true(testLogical(NA_character_)) expect_true(testLogical(NA_character_, typed.missing = FALSE)) expect_false(testLogical(NA_character_, typed.missing = TRUE)) expect_true(testLogical(character())) expect_true(testLogical(character(), typed.missing = FALSE)) expect_false(testLogical(character(), typed.missing = TRUE)) }) checkmate/tests/testthat/test_checkAtomicVector.R0000644000176200001440000000337414245411067021772 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_wf.R0000644000176200001440000000166214245411067017007 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_checkR6.R0000644000176200001440000000266314245411067017662 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_true(checkR6(x, private = character(0))) 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") }) test_that("check contents of empty private", { skip_if_not_physically_installed("R6") x = R6::R6Class("Bar", public = list(a = 5), active = list(c = function() 99) )$new() expect_false(testR6(x, private = "b")) expect_true(testR6(x, private = character(0))) }) checkmate/tests/testthat/test_checkTibble.R0000644000176200001440000000107614245411067020571 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)) expect_true(testTibble(x, max.rows = 200, max.cols = 5)) expect_false(testTibble(x, max.rows = 100)) expect_false(testTibble(x, max.cols = 3)) }) checkmate/tests/testthat/test_checkChoice.R0000644000176200001440000000307114646134572020567 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", { skip_if_not_installed("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") }) test_that("checkChoice / NAs (#158)", { expect_true(test_choice(NA_character_, NA)) expect_true(test_choice(NA, NA_character_)) }) checkmate/tests/testthat/test_qassert.R0000644000176200001440000002053514516161321020051 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 xp = as.POSIXct(Sys.time()) + 1:10; xp[5] = NA 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), regexp = 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_succ_all(xp, "p") expect_fail_all(xp, "P") 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(xd, "p") 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") }) test_that("multiple rules are correctly processed", { expect_true(qtest(1, c("M", "F", "C", "N"))) }) test_that("integer posix (#175)", { intSeq = seq(as.POSIXct("2000-01-01"), length.out = 31, by = "1 day") expect_true(qtest(intSeq, "P+")) }) checkmate/tests/testthat/test_anyNaN.R0000644000176200001440000000126314245411067017554 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_checkList.R0000644000176200001440000000264214245411067020303 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"), "numeric") expect_error(assertList(x, len = 33), "Must have length 33") expect_true(testList(list(), names = "named")) x = list(1, NULL) expect_true(testList(x)) expect_false(testList(x, any.missing = FALSE)) x = 1:3 class(x) = "foo" x = list(x, 1:3) expect_true(testList(x, types = c("foo", "integerish"))) expect_error(assertList(1), "list") }) test_that("missingness in lists", { x = list(1, NULL) expect_true(testList(x)) expect_true(testList(x, all.missing = FALSE)) expect_false(testList(x, any.missing = FALSE)) x = list(NULL) expect_true(testList(x)) expect_false(testList(x, all.missing = FALSE)) expect_false(testList(x, any.missing = FALSE)) }) checkmate/tests/testthat/test_qassertr.R0000644000176200001440000000426114245411067020235 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), regexp = 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_checkDataTable.R0000644000176200001440000000457414646134377021232 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") x = data.table::as.data.table(iris) expect_true(testDataTable(x, max.rows = 200, max.cols = 5)) expect_false(testDataTable(x, max.rows = 100)) expect_false(testDataTable(x, max.cols = 3)) }) test_that("list columns", { skip_if_not_physically_installed("data.table") x = data.table::data.table(a = 1:2, b = list(3, 4)) expect_true(testDataTable(x, any.missing = FALSE)) x$b = list(3, NULL) expect_true(testDataTable(x, any.missing = FALSE)) expect_true(testDataTable(x, all.missing = FALSE)) x$b = list(NULL, NULL) expect_true(testDataTable(x, any.missing = FALSE)) expect_true(testDataTable(x, all.missing = FALSE)) }) test_that("nrow for null data tables", { skip_if_not_physically_installed("data.table") # c.f. https://github.com/Rdatatable/data.table/issues/3149 M = matrix(1:3, nrow = 3) M = M[, integer(0)] DT = data.table::as.data.table(M) # null data table expect_true(testDataTable(DT, nrows = 0)) }) checkmate/tests/testthat/test_checkNull.R0000644000176200001440000000037214245411067020300 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_checkFilesystem.R0000644000176200001440000000576714245411067021527 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)) expect_true(checkPathForOutput("a.txt", extension = "txt")) expect_error(assertPathForOutput("a.R", extension = "txt"), "extension") }) test_that("#195", { x = tempfile(fileext = ".csv.gz") file.create(x) expect_true(test_file_exists(x, extension = ".gz")) expect_true(test_file_exists(x, extension = ".csv.gz")) }) checkmate/tests/testthat/test_checkScalarNA.R0000644000176200001440000000076514531605563021024 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") }) test_that("checkScalarNA on data.frame/data.table (#245)", { df = data.frame(x = 1:2) expect_false(testScalarNA(df)) }) checkmate/tests/testthat/test_checkComplex.R0000644000176200001440000000173514245411067021001 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") }) test_that("typed.missing", { expect_true(testComplex(NA)) expect_true(testComplex(NA, typed.missing = FALSE)) expect_false(testComplex(NA, typed.missing = TRUE)) expect_true(testComplex(character())) expect_true(testComplex(character(), typed.missing = FALSE)) expect_false(testComplex(character(), typed.missing = TRUE)) }) checkmate/tests/testthat/test_checkCharacter.R0000644000176200001440000000525514646750331021274 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)) }) test_that("Sorted strings", { x = letters[1:3] expect_true(testCharacter(x, sorted = TRUE)) expect_error(assertCharacter(rev(x), sorted = TRUE), "sorted") x = c("aaa", "aab", "aac") expect_true(testCharacter(x, sorted = TRUE)) expect_error(assertCharacter(rev(x), sorted = TRUE), "sorted") }) test_that("typed.missing", { expect_true(testCharacter(NA)) expect_true(testCharacter(NA, typed.missing = FALSE)) expect_false(testCharacter(NA, typed.missing = TRUE)) expect_true(testCharacter(logical())) expect_true(testCharacter(logical(), typed.missing = FALSE)) expect_false(testCharacter(logical(), typed.missing = TRUE)) }) checkmate/tests/testthat/test_checkEnvironment.R0000644000176200001440000000127114245411067021671 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_anyMissing.R0000644000176200001440000000457514245411067020522 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_checkPOSIXct.R0000644000176200001440000000454514245411067020625 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)) }) test_that("integer posix (#175)", { intSeq = seq(as.POSIXct("2000-01-01"), length.out = 31, by = "1 day") expect_true(test_posixct(intSeq, any.missing = FALSE, lower = intSeq[1], upper = intSeq[31])) expect_true(test_posixct(intSeq, any.missing = FALSE, lower = as.POSIXct("2000-01-01"), upper = as.POSIXct("2001-01-01"))) }) checkmate/tests/testthat/test_checkMatrix.R0000644000176200001440000000765114245411067020641 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_true(testMatrix(xe, "logical")) # empty, so all are missing 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, max.rows = 5, max.cols = 5)) 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, max.rows = 1)) expect_false(testMatrix(x, max.cols = 1)) 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))) }) test_that("missing locations are reported correctly", { x = matrix(1:12, ncol = 3); x[1, 1] = NA expect_true(grepl("row 1, col 1", checkMatrix(x, any.missing = FALSE))) x = matrix(1:12, ncol = 3); x[2, 3] = NA expect_true(grepl("row 2, col 3", checkMatrix(x, any.missing = FALSE))) x = matrix(1:12, ncol = 3); x[4, 3] = NA expect_true(grepl("row 4, col 3", checkMatrix(x, any.missing = FALSE))) }) test_that("mode accepts all missing values (#184)", { x = matrix(NA, nrow = 3, ncol = 3) expect_true(test_matrix(x, mode = "double")) }) checkmate/tests/testthat/test_checkInt.R0000644000176200001440000000225114245411067020116 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_false(is.integer(assertInt(5))) expect_true(is.integer(assertInt(5, coerce = TRUE))) 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) }) test_that("Coercion works", { expect_identical(assertInt(2, coerce = TRUE), 2L) expect_error(assertInt("lkajsd"), "single integerish") expect_error(assertInt("lkajsd"), "not 'character'") # check that names are not dropped (#157) x = c("a" = 1) expect_identical(assertInt(x, coerce = TRUE), setNames(1L, "a")) }) checkmate/tests/testthat/test_checkClass.R0000644000176200001440000000200714245411067020430 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"), "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"), "class 'c', but has class 'a'") }) checkmate/tests/testthat/test_checkTRUE.R0000644000176200001440000000026514245411067020146 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/setup.R0000644000176200001440000000024014245411067016463 0ustar liggesusersif (getRversion() >= "3.6.0") { old_opts = options( warnPartialMatchArgs = TRUE, warnPartialMatchAttr = TRUE, warnPartialMatchDollar = TRUE ) } checkmate/tests/test-all.R0000755000176200001440000000005214245411067015214 0ustar liggesuserslibrary(testthat) test_check("checkmate") checkmate/MD50000644000176200001440000003205414651705516012524 0ustar liggesusers2945ae06ae48dc954f90df4821e328a5 *DESCRIPTION 3fa047ece8f2443abd01534b78f373c5 *LICENSE 50f08001a14942d8005630fd94358e89 *NAMESPACE 2b12e70c4a3eb3b3c2e420632a80ff41 *NEWS.md f0fc2aeb92b3d2014f6357308fd80954 *R/AssertCollection.R a7fc65b769f9477797c56c8c2af12339 *R/allMissing.R d4b005e269d2845ff89bed357a4e3d5f *R/anyInfinite.R 08ad265d963c2348cdd5ed1ee35da6cf *R/anyMissing.R 65edb5b66b8a66217713a6aa2df5f3b9 *R/anyNaN.R 774b3adcff4d49e312551dd281796a7c *R/asInteger.R 0adf71ce60e155175d25cc3660fced77 *R/assert.R 06764f178bb0c2ca5bee8e7b6fb8fffd *R/checkAccess.R 69c994dac41fd093ff563a26df3372f6 *R/checkArray.R 4ec40a105219eec0c8027c108c3a3013 *R/checkAtomic.R 3159ba95fc55e588ec02cf8e7fba3013 *R/checkAtomicVector.R 8fc4580178d0f17d57c3279c26a45aba *R/checkCharacter.R 151f0057a97f8f20a2f3a61167f0f9f6 *R/checkChoice.R 433fb97e73c269555ebdb9ca0b184fef *R/checkClass.R b381cf67392ffb21a5fb09d77bd3c395 *R/checkComplex.R 18688628d514c3133a47a051a32db116 *R/checkCount.R fa9785a27b85ba608224aab0dbcebcf7 *R/checkDataFrame.R d873257563cd589aaefdf1caa0a15831 *R/checkDataTable.R a4b88ea5f0a5d376d714c8cd34399d74 *R/checkDate.R cd077c595d632832599de4082190a4a4 *R/checkDirectoryExists.R 86b6fa71452439805958cf0c060b813d *R/checkDisjunct.R e25a83502fbb80c5b7c8667aa650fa09 *R/checkDouble.R fcdac8476ee20a613a516e9d1a220456 *R/checkEnvironment.R 54378cb2e553ea81ec2ac5d3231e326d *R/checkFALSE.R c09fdf8e26ea2086e6144dfb0ed6ee1e *R/checkFactor.R 7b5e972895bde80e8a93372ccfa1d65b *R/checkFileExists.R 1702c4c5319656458a29dcf2a583ada7 *R/checkFlag.R 6f2523dcdca0680cc9ff420af17b2dbd *R/checkFormula.R 143fb83bb8384ed19b7014a096a649b3 *R/checkFunction.R 010d3b94c18be3104ce67320710dadd1 *R/checkInt.R 3f82235a659cda816e6ce80b50762258 *R/checkInteger.R c3db61c2960819707b9c0180eea32ecf *R/checkIntegerish.R 86791f0a8556010fdd5ed453a8243840 *R/checkList.R 1e59c92657a2d41170e556b6b46cb339 *R/checkLogical.R 63d09cf4637e1bf8e8d81e37966c10e1 *R/checkMatrix.R 2fa3651acabf28b9b9dff35d08c9aad8 *R/checkMultiClass.R e8144ea521e066f5f751e95a9f59aa29 *R/checkNamed.R d079bb2fbf4a4d17fd056037d2ac3d4b *R/checkNames.R 083d948350010062f75349a480a14d04 *R/checkNull.R c5d319670af3c71df9f9d7779edec535 *R/checkNumber.R 36d0fa251885c8f6f3c00687541bdb12 *R/checkNumeric.R 489644560780caf623590aa036f74ef9 *R/checkOS.R 41fe8fdbd5a9111867a3688f0baeb8a2 *R/checkPOSIXct.R 20e12b9d78c4ff7e2b4ad72cee6906e6 *R/checkPathForOutput.R 3208f9c88b5c054e281b32ac0d946eae *R/checkPermutation.R 529fdd4d18a7c1fe0f7c97c1f7897701 *R/checkR6.R 2642a4b36862ab6b9b06801163903593 *R/checkRaw.R ecf6b98d81325dce56c793e946c9e7ab *R/checkScalar.R ec4df47673572fc649be222034810925 *R/checkScalarNA.R 8b2bfe39acc0d3bb81327b92446dcac2 *R/checkSetEqual.R 69c063b8fac0d01c16223ac1d212b15d *R/checkString.R bc1ad8dbd76069a6ea34143afe3bbf8d *R/checkSubset.R 37a8a17ca8652cb5feb1bc9c3958e98e *R/checkTRUE.R 34174c8e2ee8b61dbeebfbe37ba30fb4 *R/checkTibble.R c5c5fc037f6da1a8913c98b6f557a0c8 *R/checkVector.R 80ae11a07596493bea7960e2eb65dd73 *R/coalesce.R 2f1bf08e6ce0600311efe3c663456072 *R/helper.R a2f4e6ea5fe680633166a3223e090bd1 *R/isIntegerish.R c4d7271df33b1e61dbed0052715efa26 *R/makeAssertion.R 05b1a335705692497abf5d3e3e9d5f44 *R/makeExpectation.R a6d113b401335da050b127033e8013a7 *R/makeTest.R 2bcacedd9700a3595fc4292ebf573cca *R/matchArg.R e5a4b149d401ff39b945b3b350101acf *R/qassert.R 8fe8778ba7ed85d7192891169b4bcb54 *R/qassertr.R 2f0cd13a951bd3ee3678291d40ff9842 *R/vname.R e461317d090f6344d1e56dc1cbfd4c20 *R/wfwl.R fb455c39391aa2062150038a8893080a *R/zzz.R 98ad5835faefecf58714931a9f2fe11c *README.md 333680b95c71852ee27bd64e97182eda *build/vignette.rds 8503302b8e95f52f7a083f7a53749d78 *inst/CITATION ff96d64f966d5318f56505355acd48bd *inst/doc/checkmate.R 496d009a2d4fe0411d011a9dea9780d5 *inst/doc/checkmate.Rmd 9ad31c27353677b07381d1d9f4f1ad64 *inst/doc/checkmate.html 967a7f2ba57a8cc0ba002e315009c937 *inst/doc/tinytest.R d56c423e340039ac255b90458252ec5b *inst/doc/tinytest.Rmd f610ef4be4f79b1c55e9ca9360865820 *inst/doc/tinytest.html 2b802843486b8eedf6fc7b2c73215844 *inst/include/checkmate.h 9410eaa688f6922154f59ed428acb131 *inst/include/checkmate_stub.c 570556c5f559df4b9cbc2388e9138da9 *man/AssertCollection.Rd ed7f80b05a99aa497b5c64d92afd8024 *man/anyInfinite.Rd 04e34c4649981a37c46ac588065b798a *man/anyMissing.Rd 5a8da757d242d5d2ff28254575a4adcf *man/anyNaN.Rd 9e9d74c8ab2e10ad232ea71f3321cf23 *man/asInteger.Rd a5c290d8698dc444dea63529308f8369 *man/assert.Rd b7854d74eb5570c9694d17fcaed13e4a *man/checkAccess.Rd ddb0e0530441e8bee53d581fc2bed23d *man/checkArray.Rd 7db8ef6fc5e48da9a7c68459fac443b3 *man/checkAtomic.Rd 3099ac36159a9f45cc328ac62aca0bc6 *man/checkAtomicVector.Rd 86ad6032d0d236e2605bd883d1f4059d *man/checkCharacter.Rd fc43bcfe20124ebf6d3260b261d9ff6e *man/checkChoice.Rd 8c62903fa4383a5072ebe998fed70a67 *man/checkClass.Rd 1901fdbc76368c95aa19f3ffca761e90 *man/checkComplex.Rd 6f7ea2a2f4bcd4085ebda1f3d12dd9a1 *man/checkCount.Rd 678564584ed32027e990f1ab4a5198d0 *man/checkDataFrame.Rd b81507cb80888fe025de5be6e3fa27de *man/checkDataTable.Rd 13eeb65aa2b1e57917f1a6b46effa8ea *man/checkDate.Rd e6befdff034ef41a419536ea3a38018c *man/checkDirectoryExists.Rd d81a3523773ee1660cc80a3143e30135 *man/checkDisjunct.Rd 1ab150f5338ab52932d95b02b14796a5 *man/checkDouble.Rd 0f0ef2c34638152f58a600fa33780dca *man/checkEnvironment.Rd f257676a78ae58fb23eab50993ed71a5 *man/checkFALSE.Rd 7341a84c0a956f51c35c482aa68ed380 *man/checkFactor.Rd f0b19a727571d86a5edd876a32cd1a21 *man/checkFileExists.Rd 4ee00ee7a81b3a7c24639435cf95f64e *man/checkFlag.Rd 0e0f60c2739f33794ef5d775375d1c99 *man/checkFormula.Rd 4ec27a9b61ba58c7d4900b97f3ea0647 *man/checkFunction.Rd 50232db8c474072b19280506df0e0a54 *man/checkInt.Rd 11dddedfb833c8a093038591d73a4b06 *man/checkInteger.Rd edd27bd7f5a90e545f556e8d5458be42 *man/checkIntegerish.Rd 613533c74866f2c14568ab2ac610766a *man/checkList.Rd e9f343e443d22fad24dbe48d9ed22492 *man/checkLogical.Rd 3878a601a8629cb8b2a838dfab48dddb *man/checkMatrix.Rd 5eed2e93824d3141dab0ff1bcd9a3216 *man/checkMultiClass.Rd 89f05c2780b9d74d453bc0b79b0e23d5 *man/checkNamed.Rd 3fd044de5e6ce707ca10645069ff950d *man/checkNames.Rd b0f5d51e7532747086e4073cf7eb5636 *man/checkNull.Rd 8d5a78ff2adf262e12d46d5874319ab8 *man/checkNumber.Rd b53cb8df3265fe00de1907bb65603673 *man/checkNumeric.Rd 16039e316d60f91b0f76c421c423bf4a *man/checkOS.Rd 7ad98804ea970eae1459c1f4ba1cde8c *man/checkPOSIXct.Rd d908aad97a9110fe95bb884fa0b4af7f *man/checkPathForOutput.Rd 44b21fa66315d43ab95d49dad42d7048 *man/checkPermutation.Rd aabfeeddd379def4379f7dca7adda6b7 *man/checkR6.Rd 8fc85408d6cf8cefd1de790aa25dbc62 *man/checkRaw.Rd 59b17ded464c74844dd1752742a16a1d *man/checkScalar.Rd 435bbb0da9f83800e8d0a0669d824ac0 *man/checkScalarNA.Rd c839fe22cb317e7f5c21fbeafce9ee8d *man/checkSetEqual.Rd e159f2f6e287903ec75500d5500f032b *man/checkString.Rd debbe0e000147e1f7d7614f78e64e351 *man/checkSubset.Rd 83ec22fc881ffd6a510245b761315aca *man/checkTRUE.Rd 90387f8bf58b3c399e340b391c97b2b0 *man/checkTibble.Rd 35d467e70aa955b9fee6d602e088dcb4 *man/checkVector.Rd c4419778c3e8aba9826aa8eae01b1946 *man/checkmate-package.Rd df830e7a73a97a9dcce66037219a92ab *man/coalesce.Rd 1bc40e14761aebef47147b73a5b58f89 *man/makeAssertion.Rd 494c2bc1746770cfccdafd2402f7c4f0 *man/makeExpectation.Rd a8630d8c55ee8d589b18be1d96a7bfb7 *man/makeTest.Rd 5da6ef4e2155034d75d6c4f9e7825b9c *man/matchArg.Rd f69fd2ee8d44167551aac1a61b629657 *man/qassert.Rd 2558abbf7a408685c7ed178236fd9cdc *man/qassertr.Rd 04c13e4f11622873e34f735f404b11ce *man/register_test_backend.Rd c7160018ecdaf8c566838d3f71bc9b76 *man/vname.Rd 5ca43dddbda998d18889073324aae733 *man/wf.Rd 45fee9eca7be6b3bf5897ff54c241f52 *src/all_missing.c e89ed511eb97dc6d4c0df60df7e7e38d *src/all_missing.h bf2517f2ab6acf57d65a1ec0ab957b50 *src/any_infinite.c 40955c4c8408de0849fc71b7b2f7d209 *src/any_infinite.h 3e33557dd4b31d769d824bde712b75aa *src/any_missing.c d0e3faef15112efd1b1c4bb5cc328c6a *src/any_missing.h a295c7c831cc537938adc8a461ccf81b *src/any_nan.c 29b28c13be569fc54e133373e259f37b *src/any_nan.h 5283fb10f1406f2f8d79816173b9ef3a *src/backports.h 6cff0850e36cb3347973c26c0fd8c05f *src/checks.c edb2213bce6e3f84592a2ce6580cb237 *src/checks.h 317b1b3af7733390fe38538592fdcec8 *src/find_nchar.c 5f003182a001f3dc9a99f0d198a0956e *src/find_nchar.h 379e20d399b3eca2ee0d5147454c566a *src/guess_type.c 626cdf5752ff0c365859428212510bfb *src/guess_type.h b40677bc7aa88f3aa59440e27993358a *src/helper.c 5950653d7af20771e4a1db394ca95a1d *src/helper.h 8206e1eec10932a6f4f709229ffc46b0 *src/init.c e50eeea00f9f9e4db738c834549b4d9f *src/integerish.c 2b994beb191dddac5d6aad0ef982ae99 *src/integerish.h 7d0cdf8cf4f1083a8a9ecd230dbf1e36 *src/is_sorted.c aa978813f164a58ee0a09276383958a2 *src/is_sorted.h 5094efd39ccc0f5d102fd4a7685be3c0 *src/qassert.c ec33abad14184350e1b16803ac59fc09 *src/qassert.h c1b49bf48c977983b08fbfa0e5d5f633 *src/which_first.c aa36cc7d8b08bf4cfbe6fa23f607d46b *src/which_first.h 44694bd86ba5d694433561ccfac56fc5 *tests/test-all.R 435730bb6710160965cdd6dbae57457e *tests/testthat/helper.R a2875d463f9eb0e01048162f69c4de12 *tests/testthat/setup.R 6c4c9ead37c767ddeb8061ff8c74ea4f *tests/testthat/teardown.R c74b3874797c89c2ea1cfc9592ffab6e *tests/testthat/test_AssertCollection.R 009eacba07c953825dae9733108754af *tests/testthat/test_altreps.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 b04d82a17201505f8feb953c41e1eaf3 *tests/testthat/test_assert.R 7b1fc897c76160a3e179c3b24148b657 *tests/testthat/test_checkArray.R 0b6152be67996a1041105126b578a06b *tests/testthat/test_checkAtomic.R ad416dbe956f3e6eb38ff46f77a4d8b1 *tests/testthat/test_checkAtomicVector.R 541a59abc138fd3c614cce4e5d87dda6 *tests/testthat/test_checkCharacter.R fdd0570044731f9e1907dc67c161eb49 *tests/testthat/test_checkChoice.R 6e93d0ffa46edae7777031821743ee3f *tests/testthat/test_checkClass.R c3d051855e75a63c7c9bde009386a2ac *tests/testthat/test_checkComplex.R f65d16c4f9802c45ff62c9ea264c5a73 *tests/testthat/test_checkCount.R 6ce6297d3710e3f7a50058a7a195539c *tests/testthat/test_checkDataFrame.R ed6656c85fb0f18ab7ca97f107ba87c4 *tests/testthat/test_checkDataTable.R 313830eabfe3dd1dee3fbf97de82dac6 *tests/testthat/test_checkDate.R e573b8f86b90294c92e5b791fa688a78 *tests/testthat/test_checkDisjunct.R 23db85c64ded462a0267bb96d82259bb *tests/testthat/test_checkDouble.R 34c6dc60267982609546dfc50cdc58a5 *tests/testthat/test_checkEnvironment.R f7c6ce89bbbd44374eedaef0eef2b0ce *tests/testthat/test_checkFALSE.R ba206a2254f1cb6e469f0571339cff55 *tests/testthat/test_checkFactor.R 7420634de1e8585a5a3d1ab23d015a96 *tests/testthat/test_checkFilesystem.R 2ca8bc06283a7c62bdd32f28ccdbda2a *tests/testthat/test_checkFlag.R 05785cb9cb39155726790723627b81f9 *tests/testthat/test_checkFormula.R 2828d2e24fefb8957fcc4d8579626594 *tests/testthat/test_checkFunction.R e08ef1e58036d81332bfc7df997154c5 *tests/testthat/test_checkInt.R 6ad4f2fd81f7620d25940cde84b97aef *tests/testthat/test_checkInteger.R ed9c0826c6ae3a503f1a784685614171 *tests/testthat/test_checkIntegerish.R 2091d6755da41e6930331e44d509898b *tests/testthat/test_checkList.R cc2c05a756d3bf6fd3fb0c1f8ac2b3bf *tests/testthat/test_checkLogical.R c10e216b622f512c8948d4b052d0029b *tests/testthat/test_checkMatrix.R 05ce05ad041b5f6c15a8349fe3037861 *tests/testthat/test_checkMultiClass.R eafdbf180879c3b466d7acee0846c164 *tests/testthat/test_checkNames.R 5ca56038ba855cffb5996db49724663b *tests/testthat/test_checkNull.R 522c310bf5964325aff7e7f94b89c8c8 *tests/testthat/test_checkNumber.R 2c4c21ba0b88b092e8fd88f97c1d8060 *tests/testthat/test_checkNumeric.R af4d804926a342f32ea132c81eb0e9f3 *tests/testthat/test_checkOS.R 0e5c813686d9ed56d12332d2664160ee *tests/testthat/test_checkPOSIXct.R 7444b4ea238215bb10e396cced1e6a87 *tests/testthat/test_checkPermutation.R 0569420355d062441f913ecdd9c2a374 *tests/testthat/test_checkR6.R 51166aa5b8f1b686d0a9739d93550a18 *tests/testthat/test_checkRaw.R de75d8d474ee541b05666065f39378fd *tests/testthat/test_checkScalar.R f8b999f685b2368d92f82d9989c1731e *tests/testthat/test_checkScalarNA.R a3c9f00904c8ba7ffb79ee5fb1b4437e *tests/testthat/test_checkSetEqual.R 5736a9bf58728bb88f5b5cf09f7fd3bd *tests/testthat/test_checkString.R 6fb5633bcc8a020ca9d48f4aa0a1bd50 *tests/testthat/test_checkSubset.R 2a4b87a44c90fb268588f6bf0b01beda *tests/testthat/test_checkTRUE.R 3a71fdd5c0f646d7e684da80bc6a4c1a *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 5fb8aa32c5fdbac3d180b8b183591131 *tests/testthat/test_interoperability.R 1fd86ffce5cdfaa5d5773eb5103b814c *tests/testthat/test_makeFunction.R a43ada07c4347a5d2ba63dc04d49e5a0 *tests/testthat/test_matchArg.R dd18034569cd03f574395ef2a86d87ba *tests/testthat/test_messages.R cfe101d63983a7cbe7031ad21fddbcee *tests/testthat/test_qassert.R 10f26bde50eeb476573cf51c064343a6 *tests/testthat/test_qassertr.R 98d5ba13378e03edbc92debb3f37772e *tests/testthat/test_wf.R 496d009a2d4fe0411d011a9dea9780d5 *vignettes/checkmate.Rmd d56c423e340039ac255b90458252ec5b *vignettes/tinytest.Rmd checkmate/R/0000755000176200001440000000000014646536154012415 5ustar liggesuserscheckmate/R/checkDouble.R0000644000176200001440000000306614245411067014743 0ustar liggesusers#' Check that an argument is a vector of type double #' #' @templateVar fn Double #' @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 typed.missing #' @template checker #' @family basetypes #' @useDynLib checkmate c_check_double #' @export #' @examples #' testDouble(1) #' testDouble(1L) #' testDouble(1, min.len = 1, lower = 0) checkDouble = 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, typed.missing = FALSE, null.ok = FALSE) { .Call(c_check_double, x, lower, upper, finite, any.missing, all.missing, len, min.len, max.len, unique, sorted, names, typed.missing, null.ok) } #' @export #' @rdname checkDouble check_double = checkDouble #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkDouble assertDouble = makeAssertionFunction(checkDouble, c.fun = "c_check_double", use.namespace = FALSE) #' @export #' @rdname checkDouble assert_double = assertDouble #' @export #' @include makeTest.R #' @rdname checkDouble testDouble = makeTestFunction(checkDouble, c.fun = "c_check_double") #' @export #' @rdname checkDouble test_double = testDouble #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkDouble expect_double = makeExpectationFunction(checkDouble, c.fun = "c_check_double", use.namespace = FALSE) checkmate/R/checkClass.R0000644000176200001440000000427614646535463014616 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}}. #' \code{x} must inherit from all specified classes. #' @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 #' @family classes #' @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 inherit from 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, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/anyNaN.R0000644000176200001440000000072114245411067013712 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/qassert.R0000644000176200001440000001202514245411067014210 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{[pP]} \tab POSIXct date.\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 (!isTRUE(res)) mstop(qmsg(res, .var.name), call. = sys.call(-1L)) 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 (!isTRUE(res)) 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/checkFALSE.R0000644000176200001440000000151614245411067014361 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 (isFALSE(x) || (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, use.namespace = FALSE) #' @export #' @rdname checkFALSE assert_false = assertFALSE #' @export #' @include makeTest.R #' @rdname checkFALSE testFALSE = makeTestFunction(checkFALSE) #' @export #' @rdname checkFALSE test_false = testFALSE checkmate/R/makeAssertion.R0000644000176200001440000000747014245411067015343 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 (!isTRUE(res)) { assertString(var.name, .var.name = ".var.name") if (is.null(collection)) { mstop("Assertion on '%s' failed: %s.", var.name, res, call. = sys.call(-2L)) } assertClass(collection, "AssertCollection", .var.name = "add") collection$push(sprintf("Variable '%s': %s.", var.name, res)) } return(invisible(x)) } #' @rdname makeAssertion #' @template makeFunction #' @template use.namespace #' @param coerce [\code{logical(1)}]\cr #' If \code{TRUE}, injects some lines of code to convert numeric values to integer after an successful assertion. #' Currently used in \code{\link{assertCount}}, \code{\link{assertInt}} and \code{\link{assertIntegerish}}. #' @export makeAssertionFunction = function(check.fun, c.fun = NULL, use.namespace = TRUE, coerce = FALSE, env = parent.frame()) { fun.name = if (is.character(check.fun)) check.fun else deparse(substitute(check.fun)) check.fun = match.fun(check.fun) check.args = fun.args = formals(args(check.fun)) x.name = names(fun.args[1L]) new.fun = function() TRUE body = sprintf("if (missing(%s)) stop(sprintf(\"argument \\\"%%s\\\" is missing, with no default\", .var.name))", x.name) if (is.null(c.fun)) { body = paste0(body, sprintf("; res = %s(%s)", fun.name, paste0(names(check.args), collapse = ", "))) } else { body = paste0(body, sprintf("; res = .Call(%s)", paste0(c(c.fun, names(check.args)), collapse = ", "))) } if (coerce) { fun.args = c(fun.args, alist(coerce = FALSE)) } if (use.namespace) { fun.args = c(fun.args, list(.var.name = bquote(checkmate::vname(.(as.name(x.name)))), add = NULL)) body = paste0(body, "; checkmate::makeAssertion") } else { fun.args = c(fun.args, list(.var.name = bquote(vname(.(as.name(x.name)))), add = NULL)) body = paste0(body, "; makeAssertion") } body = paste0(body, sprintf("(%s, res, .var.name, add)", x.name)) if (coerce) { body = paste0(body, "; if (isTRUE(coerce) && is.double(x)) x = setNames(as.integer(round(x, 0L)), names(x)); invisible(x)") } formals(new.fun) = fun.args body(new.fun) = parse(text = paste("{", body, "}")) environment(new.fun) = env return(new.fun) } checkmate/R/checkFunction.R0000644000176200001440000000514314245411067015314 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(args(x))) %??% character() if (length(args) == 0L) { if (length(fargs) > 0L) return("May not have any arguments") return(TRUE) } qassert(ordered, "B1") if (ordered) { if (length(fargs) < length(args) || 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(args(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, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/checkAtomicVector.R0000644000176200001440000000510614245411067016125 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 basically 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", use.namespace = FALSE) #' @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", use.namespace = FALSE) checkmate/R/AssertCollection.R0000644000176200001440000000375314646535404016022 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/checkDataTable.R0000644000176200001440000000527514245411067015356 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, max.rows = NULL, min.cols = NULL, max.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, max.rows, min.cols, max.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, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/checkLogical.R0000644000176200001440000000252514245411067015102 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 typed.missing #' @template checker #' @family basetypes #' @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, typed.missing = FALSE, null.ok = FALSE) { .Call(c_check_logical, x, any.missing, all.missing, len, min.len, max.len, unique, names, typed.missing, null.ok) } #' @export #' @rdname checkLogical check_logical = checkLogical #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkLogical assertLogical = makeAssertionFunction(checkLogical, c.fun = "c_check_logical", use.namespace = FALSE) #' @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", use.namespace = FALSE) checkmate/R/checkComplex.R0000644000176200001440000000250514245411067015135 0ustar liggesusers#' Check if an argument is a vector of type complex #' #' @templateVar fn Complex #' @template x #' @template na-handling #' @inheritParams checkVector #' @template typed.missing #' @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, typed.missing = FALSE, null.ok = FALSE) { .Call(c_check_complex, x, any.missing, all.missing, len, min.len, max.len, unique, names, typed.missing, null.ok) } #' @export #' @rdname checkComplex check_complex = checkComplex #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkComplex assertComplex = makeAssertionFunction(checkComplex, c.fun = "c_check_complex", use.namespace = FALSE) #' @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", use.namespace = FALSE) checkmate/R/checkScalar.R0000644000176200001440000000207514245411067014735 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", use.namespace = FALSE) #' @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", use.namespace = FALSE) checkmate/R/checkVector.R0000644000176200001440000000425414245411067014773 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? If \code{TRUE}, mimics the behavior of #' \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 no non-missing values allowed? Default is \code{TRUE}. #' Note that empty vectors do not have non-missing values. #' @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", use.namespace = FALSE) #' @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 checkmate/R/checkSubset.R0000644000176200001440000000323414245411067014773 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", set_collapse(choices))) return(TRUE) } if (isTRUE(fmatch) && requireNamespace("fastmatch", quietly = TRUE)) match = fastmatch::fmatch check_subset_internal(x, choices, match) } #' @export #' @rdname checkSubset check_subset = checkSubset #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkSubset assertSubset = makeAssertionFunction(checkSubset, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/checkIntegerish.R0000644000176200001440000000372114245411067015630 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 sufficiently close to an #' integer w.r.t. a numeric tolerance `tol`. #' #' @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 coerce #' @template typed.missing #' @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, typed.missing = FALSE, null.ok = FALSE) { .Call(c_check_integerish, x, tol, lower, upper, any.missing, all.missing, len, min.len, max.len, unique, sorted, names, typed.missing, null.ok) } #' @export #' @rdname checkIntegerish check_integerish = checkIntegerish #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkIntegerish assertIntegerish = makeAssertionFunction(checkIntegerish, c.fun = "c_check_integerish", use.namespace = FALSE, coerce = TRUE) #' @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", use.namespace = FALSE) checkmate/R/anyInfinite.R0000644000176200001440000000100314245411067014775 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/R/allMissing.R0000644000176200001440000000054014646535350014636 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/checkDirectoryExists.R0000644000176200001440000000413214245411067016670 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 exist", 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, use.namespace = FALSE) #' @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, use.namespace = FALSE) #' @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/qassertr.R0000644000176200001440000000454414245411067014401 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 (!isTRUE(res)) mstop(qrmsg(x, res, .var.name), call. = sys.call(-1L)) 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 (!isTRUE(res)) 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/checkScalarNA.R0000644000176200001440000000233714531605563015161 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 (!is.atomic(x) || 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, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/makeTest.R0000644000176200001440000000353014245411067014304 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) { isTRUE(res) } #' @rdname makeTest #' @template makeFunction #' @export makeTestFunction = function(check.fun, c.fun = NULL, env = parent.frame()) { fun.name = if (is.character(check.fun)) check.fun else deparse(substitute(check.fun)) check.fun = match.fun(check.fun) fun.args = formals(args(check.fun)) new.fun = function() TRUE formals(new.fun) = fun.args if (is.null(c.fun)) { body = paste0("isTRUE(", fun.name, "(", paste0(names(fun.args), collapse = ", "), "))") } else { body = paste0("isTRUE(.Call(", paste0(c(c.fun, names(fun.args)), collapse = ", "), "))") } body(new.fun) = parse(text = paste("{", body, "}")) environment(new.fun) = env return(new.fun) } checkmate/R/checkArray.R0000644000176200001440000000313414245411067014603 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", use.namespace = FALSE) #' @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", use.namespace = FALSE) checkmate/R/checkInt.R0000644000176200001440000000225214245411067014257 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 coerce #' @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", use.namespace = FALSE, coerce = TRUE) #' @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", use.namespace = FALSE) checkmate/R/helper.R0000644000176200001440000000512514646536123014016 0ustar liggesusersmstop = function(msg, ..., call. = NULL) { stop(simpleError(sprintf(msg, ...), call.)) } "%and%" = function(lhs, rhs) { if (isTRUE(lhs)) 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)) } array_collapse = function(x) { if (length(x) == 0L) return("[]") sprintf("['%s']", paste0(x, collapse = "','")) } capitalize = function(x) { substr(x, 1L, 1L) = toupper(substr(x, 1L, 1L)) x } set_collapse = function(x) { if (length(x) == 0L) return("{}") sprintf("{'%s'}", paste0(unique(x), collapse = "','")) } set_msg = function(msg, what, ...) { if (is.null(what)) { sprintf(capitalize(msg), ...) } else { paste(capitalize(what), sprintf(msg, ...)) } } check_subset_internal = function(x, choices, match, what = NULL) { qassert(choices, "a") if (length(choices) == 0L) { if (length(x) == 0L) return(TRUE) return(set_msg("must be a subset of the empty set, i.e. also empty", what)) } if (!is.null(x)) { if (!isSameType(x, choices) && !allMissing(x)) { return(set_msg("must be a subset of %s, but has different type", what, set_collapse(choices))) } ii = match(x, choices) if (anyMissing(ii)) { return(set_msg( "must be a subset of %s, but has additional elements %s", what, set_collapse(choices), set_collapse(x[is.na(ii)]) )) } } return(TRUE) } check_set_equal_internal = function(x, y, match, what = NULL) { if ((!isSameType(x, y) && !allMissing(x))) { return(set_msg("Must be setequal to %s, but has different type", what, set_collapse(y))) } ii = match(x, y) if (anyMissing(ii)) { return(set_msg("must be a permutation of set %s, but has extra elements %s", what, set_collapse(y), set_collapse(x[is.na(ii)]) )) } ii = match(y, x) if (anyMissing(ii)) { return(set_msg("must be a set equal to %s, but is missing elements %s", what, set_collapse(y), set_collapse(y[is.na(ii)]) )) } return(TRUE) } check_disjunct_internal = function(x, y, match, what = NULL) { if (length(x) == 0L || length(y) == 0L) { return(TRUE) } ii = match(x, y, 0L) > 0L if (any(ii)) { return(set_msg("must be disjunct from %s, but has elements %s", what, set_collapse(y), set_collapse(x[ii]) )) } return(TRUE) } checkmate/R/checkSetEqual.R0000644000176200001440000000345114422167153015253 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, but is %s", array_collapse(y), array_collapse(x))) return(TRUE) } if (isTRUE(fmatch) && requireNamespace("fastmatch", quietly = TRUE)) match = fastmatch::fmatch check_set_equal_internal(x, y, match) } #' @export #' @rdname checkSetEqual check_set_equal = checkSetEqual #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkSetEqual assertSetEqual = makeAssertionFunction(checkSetEqual, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/checkR6.R0000644000176200001440000000533714245411067014023 0ustar liggesusers#' Check if an argument is an 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 #' @family classes #' @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") penv = x$.__enclos_env__[["private"]] %??% new.env() if (is.null(penv)) { i = if (length(private)) 1L else integer(0L) } else { i = wf(private %nin% ls(penv, 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, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/coalesce.R0000644000176200001440000000115114245411067014302 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/checkRaw.R0000644000176200001440000000274414245411067014264 0ustar liggesusers#' Check if an argument is a raw vector #' #' @templateVar fn Raw #' @template x #' @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 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 #' @useDynLib checkmate c_check_raw #' @export #' @examples #' testRaw(as.raw(2), min.len = 1L) checkRaw = function(x, len = NULL, min.len = NULL, max.len = NULL, names = NULL, null.ok = FALSE) { .Call(c_check_raw, x, len, min.len, max.len, names, null.ok) } #' @export #' @rdname checkRaw check_raw = checkRaw #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkRaw assertRaw = makeAssertionFunction(checkRaw, c.fun = "c_check_raw", use.namespace = FALSE) #' @export #' @rdname checkRaw assert_raw = assertRaw #' @export #' @include makeTest.R #' @rdname checkRaw testRaw = makeTestFunction(checkRaw, c.fun = "c_check_raw") #' @export #' @rdname checkRaw test_raw = testRaw #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkRaw expect_raw = makeExpectationFunction(checkRaw, c.fun = "c_check_raw", use.namespace = FALSE) checkmate/R/zzz.R0000644000176200001440000001020514646536154013373 0ustar liggesusers#' @section 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}}} #' } #' #' @section Check vectors: #' \itemize{ #' \item{\code{\link{checkLogical}}} #' \item{\code{\link{checkNumeric}}} #' \item{\code{\link{checkDouble}}} #' \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{checkPOSIXct}}} #' \item{\code{\link{checkVector}}} #' \item{\code{\link{checkAtomic}}} #' \item{\code{\link{checkAtomicVector}}} #' \item{\code{\link{checkRaw}}} #' } #' #' @section Check attributes: #' \itemize{ #' \item{\code{\link{checkClass}}} #' \item{\code{\link{checkMultiClass}}} #' \item{\code{\link{checkNames}}} #' \item{\code{\link{checkNamed}}} (deprecated) #' } #' #' @section Check compound types: #' \itemize{ #' \item{\code{\link{checkArray}}} #' \item{\code{\link{checkDataFrame}}} #' \item{\code{\link{checkMatrix}}} #' } #' #' @section Check other built-in R types: #' \itemize{ #' \item{\code{\link{checkDate}}} #' \item{\code{\link{checkEnvironment}}} #' \item{\code{\link{checkFunction}}} #' \item{\code{\link{checkFormula}}} #' \item{\code{\link{checkNull}}} #' } #' #' @section Check sets: #' \itemize{ #' \item{\code{\link{checkChoice}}} #' \item{\code{\link{checkSubset}}} #' \item{\code{\link{checkSetEqual}}} #' \item{\code{\link{checkDisjunct}}} #' \item{\code{\link{checkPermutation}}} #' } #' #' @section File IO: #' \itemize{ #' \item{\code{\link{checkFileExists}}} #' \item{\code{\link{checkDirectoryExists}}} #' \item{\code{\link{checkPathForOutput}}} #' \item{\code{\link{checkAccess}}} #' } #' #' @section Popular data types of third party packages: #' \itemize{ #' \item{\code{\link{checkDataTable}}} #' \item{\code{\link{checkR6}}} #' \item{\code{\link{checkTibble}}} #' } #' #' @section Safe coercion to integer: #' \itemize{ #' \item{\code{\link{asCount}}} #' \item{\code{\link{asInt}}} #' \item{\code{\link{asInteger}}} #' } #' #' @section Quick argument checks using a DSL: #' \itemize{ #' \item{\code{\link{qassert}}} #' \item{\code{\link{qassertr}}} #' } #' #' @section 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 #' @importFrom stats setNames "_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 )) register_tinytest = function() { ns = getNamespace("checkmate") expectations = names(ns)[grepl("^expect_", names(ns))] tinytest::register_tinytest_extension("checkmate", expectations) } .onLoad = function(libpath, pkgname) { backports::import(pkgname) if ("tinytest" %in% loadedNamespaces()) register_tinytest() setHook(packageEvent("tinytest", "onLoad"), function(...) register_tinytest(), action = "append") } .onUnload = function(libpath) { library.dynam.unload("checkmate", libpath) # nocov } checkmate/R/checkPOSIXct.R0000644000176200001440000000326614245411067014764 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", use.namespace = FALSE) #' @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", use.namespace = FALSE) checkmate/R/checkString.R0000644000176200001440000000254514646536033015006 0ustar liggesusers#' Check if an argument is a string #' #' @description #' A string is defined as a scalar character vector. #' To check for vectors of arbitrary length, see \code{\link{checkCharacter}}. #' #' @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, n.chars = NULL, min.chars = NULL, max.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE) { .Call(c_check_string, x, na.ok, n.chars, min.chars, max.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, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/checkFileExists.R0000644000176200001440000000501214646535637015620 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+") ii = Reduce(`|`, lapply(tolower(extension), endsWith, x = tolower(x))) if (!all(ii)) return(sprintf( "File extension must be in {'%s'} (case insensitive), but file name is '%s'", paste0(extension, collapse = "','"), x[wf(!ii)] )) } return(TRUE) } #' @export #' @rdname checkFileExists check_file_exists = checkFileExists #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkFileExists assertFileExists = makeAssertionFunction(checkFileExists, use.namespace = FALSE) #' @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, use.namespace = FALSE) #' @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 expect_file = expect_file_exists checkmate/R/checkFlag.R0000644000176200001440000000207114245411067014375 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", use.namespace = FALSE) #' @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", use.namespace = FALSE) checkmate/R/checkNumeric.R0000644000176200001440000000355514245411067015136 0ustar liggesusers#' Check that an argument is a vector of type numeric #' #' @description #' Vectors of storage type \dQuote{integer} and \dQuote{double} count as \dQuote{numeric}, c.f. \code{\link[base]{is.numeric}}. #' To explicitly check for real integer or double vectors, see \code{\link{checkInteger}}, \code{\link{checkIntegerish}} or #' \code{\link{checkDouble}}. #' #' @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 typed.missing #' @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, typed.missing = FALSE, null.ok = FALSE) { .Call(c_check_numeric, x, lower, upper, finite, any.missing, all.missing, len, min.len, max.len, unique, sorted, names, typed.missing, null.ok) } #' @export #' @rdname checkNumeric check_numeric = checkNumeric #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkNumeric assertNumeric = makeAssertionFunction(checkNumeric, c.fun = "c_check_numeric", use.namespace = FALSE) #' @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", use.namespace = FALSE) checkmate/R/checkDisjunct.R0000644000176200001440000000247514245411067015317 0ustar liggesusers#' Check if an argument is disjunct from a given set #' #' @templateVar fn Disjunct #' @template x #' @param y [\code{atomic}]\cr #' Other Set. #' @template fmatch #' @template checker #' @template set #' @family set #' @export #' @examples #' testDisjunct(1L, letters) #' testDisjunct(c("a", "z"), letters) #' #' # x is not converted before the comparison (except for numerics) #' testDisjunct(factor("a"), "a") #' testDisjunct(1, "1") #' testDisjunct(1, as.integer(1)) checkDisjunct = function(x, y, fmatch = FALSE) { qassert(x, "a") qassert(y, "a") if (isTRUE(fmatch) && requireNamespace("fastmatch", quietly = TRUE)) match = fastmatch::fmatch check_disjunct_internal(x, y, match) } #' @export #' @rdname checkDisjunct check_disjunct = checkDisjunct #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkDisjunct assertDisjunct = makeAssertionFunction(checkDisjunct, use.namespace = FALSE) #' @export #' @rdname checkDisjunct assert_disjunct = assertDisjunct #' @export #' @include makeTest.R #' @rdname checkDisjunct testDisjunct = makeTestFunction(checkDisjunct) #' @export #' @rdname checkDisjunct test_disjunct = testDisjunct #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkDisjunct expect_disjunct = makeExpectationFunction(checkDisjunct, use.namespace = FALSE) checkmate/R/checkCharacter.R0000644000176200001440000000615214646535441015434 0ustar liggesusers#' Check if an argument is a vector of type character #' #' @description #' To check for scalar strings, see \code{\link{checkString}}. #' #' @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 n.chars [\code{integer(1)}]\cr #' Exact number of characters for each element of \code{x}. #' @param min.chars [\code{integer(1)}]\cr #' Minimum number of characters for each element of \code{x}. #' @param max.chars [\code{integer(1)}]\cr #' Maximum number of characters for each element of \code{x}. #' @template sorted #' @template typed.missing #' @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, n.chars = NULL, min.chars = NULL, max.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, sorted = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE) { .Call(c_check_character, x, n.chars, min.chars, max.chars, any.missing, all.missing, len, min.len, max.len, unique, sorted, names, typed.missing, 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, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/matchArg.R0000644000176200001440000000261314245411067014256 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/checkFormula.R0000644000176200001440000000313714245411067015135 0ustar liggesusers#' Check if an argument is a formula #' #' @templateVar fn Formula #' @template x #' @template null.ok #' @template checker #' @family basetypes #' @export #' @examples #' f = Species ~ Sepal.Length + Sepal.Width #' checkFormula(f) checkFormula = function(x, null.ok = FALSE) { if (is.null(x)) { if (null.ok) return(TRUE) return("Must be a formula, not 'NULL'") } if (!inherits(x, "formula")) return(sprintf("Must be a formula%s, not %s", if (null.ok) " (or 'NULL')" else "", guessType(x))) # if (!is.null(response)) { # qassert(response, "B1") # if (response) { # if (length(lhs.formula(f)) == 0L) # return("Must have response (left hand side)") # } else { # if (length(lhs.formula(f)) > 0L) # return("May not have a response (left hand side)") # } # } return(TRUE) } # lhs.formula = function(x) { # if (length(x) == 2L) character(0L) else all.vars(x[[2L]]) # } # rhs.formula = function(x) { # all.vars(x[[length(x)]]) # } #' @export #' @rdname checkFormula check_formula = checkFormula #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkFormula assertFormula = makeAssertionFunction(checkFormula, use.namespace = FALSE) #' @export #' @rdname checkFormula assert_formula = assertFormula #' @export #' @include makeTest.R #' @rdname checkFormula testFormula = makeTestFunction(checkFormula) #' @export #' @rdname checkFormula test_formula = testFormula #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkFormula expect_formula = makeExpectationFunction(checkFormula, use.namespace = FALSE) checkmate/R/checkNull.R0000644000176200001440000000156614245411067014446 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, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/checkNamed.R0000644000176200001440000000332614245411067014554 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(new = "checkNames", old = "checkNamed", package = "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", use.namespace = FALSE) #' @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", use.namespace = FALSE) checkmate/R/checkChoice.R0000644000176200001440000000356514245411067014727 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'", set_collapse(choices))) } qassert(choices, "a") if (!qtest(x, "a1")) return(sprintf("Must be element of set %s, but is not atomic scalar", set_collapse(choices))) if (!isSameType(x, choices) && !allMissing(x)) return(sprintf("Must be element of set %s, but types do not match (%s != %s)", set_collapse(choices), 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'", set_collapse(choices), x)) return(TRUE) } #' @export #' @rdname checkChoice check_choice = checkChoice #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkChoice assertChoice = makeAssertionFunction(checkChoice, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/anyMissing.R0000644000176200001440000000237014245411067014651 0ustar liggesusers#' Check if an object contains missing values #' #' @description #' \code{anyMissing} checks for the presence of at least one missing value, #' \code{allMissing} checks for the presence of at least one non-missing value. #' 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 at least #' 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/checkFactor.R0000644000176200001440000000702014646535542014753 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, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/checkMatrix.R0000644000176200001440000000500114245411067014764 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 max.rows [\code{integer(1)}]\cr #' Maximum number of rows. #' @param min.cols [\code{integer(1)}]\cr #' Minimum number of columns. #' @param max.cols [\code{integer(1)}]\cr #' Maximum 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, max.rows = NULL, min.cols = NULL, max.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, max.rows, min.cols, max.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", use.namespace = FALSE) #' @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", use.namespace = FALSE) checkmate/R/vname.R0000644000176200001440000000073514245411067013641 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(eval.parent(substitute(substitute(x))), width.cutoff = 500L), collapse = "\n") } checkmate/R/asInteger.R0000644000176200001440000000404214245411067014447 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. #' #' Note that these functions may be deprecated in the future. #' Instead, it is advised to use \code{\link{assertCount}}, #' \code{\link{assertInt}} or \code{\link{assertIntegerish}} with #' argument \code{coerce} set to \code{TRUE} instead. #' #' @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/checkNumber.R0000644000176200001440000000236514245411067014762 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", use.namespace = FALSE) #' @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", use.namespace = FALSE) checkmate/R/checkOS.R0000644000176200001440000000230314245411067014043 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/checkDate.R0000644000176200001440000000457014245411067014407 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, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/checkPermutation.R0000644000176200001440000000501514423162567016042 0ustar liggesusers#' Check if the arguments are permutations of each other. #' #' @description #' In contrast to \code{\link{checkSetEqual}}, the function tests for a true #' permutation of the two vectors and also considers duplicated values. #' Missing values are being treated as actual values by default. #' Does not work on raw values. #' #' @templateVar fn Permutation #' @template x #' @param y [\code{atomic}]\cr #' Vector to compare with. Atomic vector of type other than raw. #' @param na.ok [\code{logical(1)}]\cr #' Are missing values allowed? Default is \code{TRUE}. #' @template checker #' @template set #' @family set #' @export #' @examples #' testPermutation(letters[1:2], letters[2:1]) #' testPermutation(letters[c(1, 1, 2)], letters[1:2]) #' testPermutation(c(NA, 1, 2), c(1, 2, NA)) #' testPermutation(c(NA, 1, 2), c(1, 2, NA), na.ok = FALSE) checkPermutation = function(x, y, na.ok = TRUE) { qassert(x, "a") qassert(y, "a") if (is.raw(x) || is.raw(y)) { stop("Cannot check permutation on raw vectors") } # These are the cheap checks that we perform separately if (!isSameType(x, y) || length(x) != length(y)) { return(sprintf("Must be permutation of %s, but is %s", array_collapse(y), array_collapse(x))) } if (!na.ok && (anyNA(x) || anyNA(y))) { return("The parameter na.ok is set to FALSE but NAs were found.") } # This drops NAs xs = sort(x) ys = sort(y) # We handle NAs and the remaining non-NAs differently: # * NA: If na.ok is TRUE, the two vector must have the same number of NAs, this is checked by # comparing the lengths, because the NAs are dropped in the sort above. # * non-NA: We sort the vector and check for equality (without NAs) if (length(xs) != length(ys) || any(xs != ys)) { return(sprintf("Must be permutation of %s, but is %s", array_collapse(ys), array_collapse(xs))) } return(TRUE) } #' @export #' @rdname checkPermutation check_permutation = checkPermutation #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkPermutation assertPermutation = makeAssertionFunction(checkPermutation, use.namespace = FALSE) #' @export #' @rdname checkPermutation assert_permutation = assertPermutation #' @export #' @include makeTest.R #' @rdname checkPermutation testPermutation = makeTestFunction(checkPermutation) #' @export #' @rdname checkPermutation test_permutation = testPermutation #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkPermutation expect_permutation = makeExpectationFunction(checkPermutation, use.namespace = FALSE) checkmate/R/checkTRUE.R0000644000176200001440000000146714245411067014313 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 (isTRUE(x) || (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, use.namespace = FALSE) #' @export #' @rdname checkTRUE assert_true = assertTRUE #' @export #' @include makeTest.R #' @rdname checkTRUE testTRUE = makeTestFunction(checkTRUE) #' @export #' @rdname checkTRUE test_true = testTRUE checkmate/R/checkInteger.R0000644000176200001440000000301614245411067015121 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 typed.missing #' @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, typed.missing = FALSE, null.ok = FALSE) { .Call(c_check_integer, x, lower, upper, any.missing, all.missing, len, min.len, max.len, unique, sorted, names, typed.missing, null.ok) } #' @export #' @rdname checkInteger check_integer = checkInteger #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkInteger assertInteger = makeAssertionFunction(checkInteger, c.fun = "c_check_integer", use.namespace = FALSE) #' @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", use.namespace = FALSE) checkmate/R/makeExpectation.R0000644000176200001440000001133714245411067015654 0ustar liggesuserstest_backend = new.env(parent = emptyenv()) #' @title Select Backend for Unit Tests #' #' @description #' Allows to explicitly select a backend for the unit tests. #' Currently supported are \code{"testthat"} and \code{"tinytest"}. #' The respective package must be installed and are loaded (but not attached). #' #' If this function is not explicitly called, defaults to \code{"testthat"} unless #' the \code{"tinytest"}'s namespace is loaded. #' #' @param name [\code{character(1)}]\cr #' \code{"testthat"} or \code{"tinytest"}. #' @return \code{NULL} (invisibly). #' @export register_test_backend = function(name) { name = match.arg(name, c("testthat", "tinytest")) if (name == "testthat") { requireNamespace("testthat") test_backend$name = "testthat" } else { requireNamespace("tinytest") test_backend$name = "tinytest" } invisible(NULL) } detect_test_backend = function() { if ("tinytest" %in% .packages()) return("tinytest") return("testthat") } get_test_backend = function() { if (is.null(test_backend$name)) { test_backend$name = detect_test_backend() register_test_backend(test_backend$name) } test_backend$name } #' @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) { backend = get_test_backend() if (backend == "testthat") { if (!requireNamespace("testthat", quietly = TRUE)) stop("Package 'testthat' is required for checkmate's 'expect_*' extensions with backend 'testthat'") if (!is.null(info)) { info = sprintf("Additional info: %s", info) } if (isTRUE(res)) { testthat::succeed(info = info) } else { testthat::fail(sprintf("Check on '%s' failed: %s", label, res), info = info) } invisible(x) } else { if (!requireNamespace("tinytest", quietly = TRUE)) stop("Package 'tinytest' is required for checkmate's 'expect_*' extensions with backend 'tinytest'") call = sys.call(sys.parent(1L)) if (isTRUE(res)) { tinytest::tinytest(TRUE, call = call) } else { tinytest::tinytest(FALSE, call = call, diff = if (is.character(res)) res else "", info = if (is.null(info)) NA_character_ else info, short = "data" ) } } } #' @rdname makeExpectation #' @template makeFunction #' @template use.namespace #' @export makeExpectationFunction = function(check.fun, c.fun = NULL, use.namespace = FALSE, env = parent.frame()) { fun.name = if (!is.character(check.fun)) deparse(substitute(check.fun)) else check.fun check.fun = match.fun(check.fun) check.args = fun.args = formals(args(check.fun)) x.name = names(fun.args[1L]) x = NULL new.fun = function() TRUE body = sprintf("if (missing(%s)) stop(sprintf(\"Argument '%%s' is missing\", label))", x.name) if (is.null(c.fun)) { body = paste0(body, sprintf("; res = %s(%s)", fun.name, paste0(names(check.args), collapse = ", "))) } else { body = paste0(body, sprintf("; res = .Call(%s)", paste0(c(c.fun, names(check.args)), collapse = ", "))) } if (use.namespace) { formals(new.fun) = c(fun.args, alist(info = NULL, label = checkmate::vname(x))) body = paste0(body, "; checkmate::makeExpectation") } else { formals(new.fun) = c(fun.args, alist(info = NULL, label = vname(x))) body = paste0(body, "; makeExpectation") } body = paste0(body, sprintf("(%s, res, info, label)", x.name)) body(new.fun) = parse(text = paste("{", body, "}")) environment(new.fun) = env return(new.fun) } checkmate/R/checkPathForOutput.R0000644000176200001440000000453114531605563016317 0ustar liggesusers#' @title Check if a path is suited for creating an output file #' #' @description #' Check if a file path can be used safely 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}. #' @param extension [\code{character(1)}]\cr #' Extension of the file, e.g. \dQuote{txt} or \dQuote{tar.gz}. #' @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, extension = NULL) { 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])) } if (!is.null(extension)) { qassert(extension, "S1") if (!endsWith(x, paste0(".", extension))) return(sprintf("File must have extension '.%s'", extension)) } return(checkAccess(dn, "w")) } #' @export #' @rdname checkPathForOutput check_path_for_output = checkPathForOutput #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkPathForOutput assertPathForOutput = makeAssertionFunction(checkPathForOutput, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/assert.R0000644000176200001440000000703014646535371014041 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 assert #' @return Throws an error (or pushes the error message to an #' \code{\link{AssertCollection}} if \code{add} is not \code{NULL}) #' if the checks fail and invisibly returns \code{TRUE} otherwise. #' @export #' @examples #' x = 1:10 #' assert(checkNull(x), checkInteger(x, any.missing = FALSE)) #' collection <- makeAssertCollection() #' assert(checkChoice(x, c("a", "b")), checkDataFrame(x), add = collection) #' collection$getMessages() assert = function(..., combine = "or", .var.name = NULL, add = NULL) { assertChoice(combine, c("or", "and")) assertClass(add, "AssertCollection", .var.name = "add", null.ok = TRUE) dots = match.call(expand.dots = FALSE)$... assertCharacter(.var.name, null.ok = TRUE, min.len = 1L, max.len = length(dots)) env = parent.frame() if (combine == "or") { msgs = character(length(dots)) for (i in seq_along(dots)) { val = eval(dots[[i]], envir = env) if (isTRUE(val)) 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") } mstopOrPush(res = msgs, v_name = .var.name, collection = add) } else { for (i in seq_along(dots)) { val = eval(dots[[i]], envir = env) if (!isTRUE(val)) { if (is.null(.var.name)) .var.name = as.character(dots[[i]])[2L] mstopOrPush(res = val, v_name = .var.name, collection = add) } } } invisible(TRUE) } # Error handling in assert() # # Internal helper function to handle errors in assert(). # @param res [character(1)}]\cr # error message # @param v_name [\code{character}]\cr # Name(s) of the variable(s) whose assertion failed. # @param collection [\code{AssertCollection} | \code{NULL}]\cr # See AssertCollection. # @return mstopOrPush() throws an exception by calling # mstop() if 'collection' is NULL, or # pushes the error message to the collection otherwise. # @keywords internal mstopOrPush = function(res, v_name, collection = NULL) { if (!is.null(collection)) { v_name = sort(unique(v_name)) prefix = if (length(v_name) > 1L) { sprintf( "Variables %s", paste0(shQuote(v_name), collapse = ", ") ) } else { sprintf("Variable '%s'", v_name) } collection$push(sprintf("%s: %s.", prefix, res)) } else if (length(v_name) > 1L) { mstop("Assertion failed. %s", res) } else { mstop("Assertion on '%s' failed: %s.", v_name, res) } } checkmate/R/checkTibble.R0000644000176200001440000000330714245411067014730 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, max.rows = NULL, min.cols = NULL, max.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, max.rows, min.cols, max.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, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/wfwl.R0000644000176200001440000000157214245411067013512 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/isIntegerish.R0000644000176200001440000000024014245411067015157 0ustar liggesusers#' @useDynLib checkmate c_is_integerish isIntegerish = function(x, tol = sqrt(.Machine$double.eps)) { tol = as.double(tol) .Call(c_is_integerish, x, tol) } checkmate/R/checkCount.R0000644000176200001440000000254614264222022014613 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 coerce #' @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", coerce = TRUE, use.namespace = FALSE) #' @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", use.namespace = FALSE) checkmate/R/checkList.R0000644000176200001440000000616314646535712014456 0ustar liggesusers#' Check if an argument is a list #' #' @note #' Contrary to R's \code{\link[base]{is.list}}, objects of type \code{\link[base]{data.frame}} #' and \code{\link[base]{pairlist}} are not recognized as list. #' #' Missingness is defined here as elements of the list being \code{NULL}, analogously to \code{\link{anyMissing}}. #' #' The test for uniqueness does differentiate between the different NA types which are built-in in R. #' This is required 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 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")) #' #' # Missingness #' testList(list(1, NA), any.missing = FALSE) #' testList(list(1, NULL), any.missing = FALSE) #' #' # 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 (length(x) == 0L || 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) } sprintf("May only contain the following types: {%s}, but element %i has type '%s'", paste0(types, collapse = ","), ind[1L], paste0(class(x[[ind[1L]]]), collapse = ",")) } #' @export #' @rdname checkList check_list = checkList #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkList assertList = makeAssertionFunction(checkList, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/checkMultiClass.R0000644000176200001440000000305714646535735015627 0ustar liggesusers#' Check the class membership of an argument #' #' @templateVar fn MultiClass #' @template x #' @param classes [\code{character}]\cr #' Class names to check for inheritance with \code{\link[base]{inherits}}. #' \code{x} must inherit from any of the specified classes. #' @template null.ok #' @template checker #' @family attributes #' @family classes #' @export #' @examples #' x = 1 #' class(x) = "bar" #' checkMultiClass(x, c("foo", "bar")) #' checkMultiClass(x, c("foo", "foobar")) checkMultiClass = function(x, classes, null.ok = FALSE) { qassert(classes, "S+") qassert(null.ok, "B1") if (is.null(x) && null.ok) return(TRUE) if (!inherits(x, classes)) { cl = class(x) return(sprintf( "Must inherit from class '%s', but has class%s '%s'", paste0(classes, collapse = "'/'"), if (length(cl) > 1L) "es" else "", paste0(cl, collapse = "','") )) } return(TRUE) } #' @export #' @rdname checkMultiClass check_multi_class = checkMultiClass #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkMultiClass assertMultiClass = makeAssertionFunction(checkMultiClass, use.namespace = FALSE) #' @export #' @rdname checkMultiClass assert_multi_class = assertMultiClass #' @export #' @include makeTest.R #' @rdname checkMultiClass testMultiClass = makeTestFunction(checkMultiClass) #' @export #' @rdname checkMultiClass test_multi_class = testMultiClass #' @export #' @include makeExpectation.R #' @template expect #' @rdname checkMultiClass expect_multi_class = makeExpectationFunction(checkMultiClass, use.namespace = FALSE) checkmate/R/checkAccess.R0000644000176200001440000000402014245411067014721 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, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/checkDataFrame.R0000644000176200001440000000311114646535516015357 0ustar liggesusers#' Check if an argument is a data frame #' #' @templateVar fn DataFrame #' @template x #' @param all.missing [\code{logical(1)}]\cr #' Are columns with only missing values allowed? Default is \code{TRUE}. #' @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, max.rows = NULL, min.cols = NULL, max.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, max.rows, min.cols, max.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, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/checkNames.R0000644000176200001440000001105614646535767014615 0ustar liggesusers#' Check names to comply to specific rules #' #' @description #' Performs various checks on character vectors, usually names. #' #' @templateVar fn Names #' @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._]*$}.} #' \item{ids:}{Same as \dQuote{strict}, but does not enforce uniqueness.} #' } #' 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. #' @param disjunct.from [\code{character}]\cr #' Names provided in \code{x} must may not be present in the vector \code{disjunct.from}. #' @param what [\code{character(1)}]\cr #' Type of name vector to check, e.g. \dQuote{names} (default), \dQuote{colnames} or \dQuote{rownames}. #' @template checker #' @useDynLib checkmate c_check_names #' @family attributes #' @export #' @examples #' x = 1:3 #' testNames(names(x), "unnamed") #' names(x) = letters[1:3] #' testNames(names(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, disjunct.from = NULL, what = "names") { .Call(c_check_names, x, type, what) %and% checkNamesCmp(x, subset.of, must.include, permutation.of, identical.to, disjunct.from, what) } checkNamesCmp = function(x, subset.of, must.include, permutation.of, identical.to, disjunct.from, what) { if (!is.null(subset.of)) { qassert(subset.of, "S") msg = check_subset_internal(x, subset.of, match, what) if (!isTRUE(msg)) return(msg) } if (!is.null(must.include)) { qassert(must.include, "S") ii = match(must.include, x) if (anyMissing(ii)) { return(set_msg("must include the elements %s, but is missing elements %s", what, set_collapse(must.include), set_collapse(must.include[is.na(ii)]) )) } } if (!is.null(permutation.of)) { permutation.of = unique(qassert(permutation.of, "S")) msg = check_set_equal_internal(x, permutation.of, match, what) if (!isTRUE(msg)) return(msg) } if (!is.null(identical.to)) { qassert(identical.to, "S") if (!identical(x, identical.to)) { return(set_msg("must be a identical to set %s, but is %s", what, set_collapse(identical.to), set_collapse(x) )) } } if (!is.null(disjunct.from)) { qassert(disjunct.from, "S") msg = check_disjunct_internal(x, disjunct.from, match, what) if (!isTRUE(msg)) return(msg) } return(TRUE) } #' @export #' @rdname checkNames check_names = checkNames #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkNames assertNames = makeAssertionFunction(checkNames, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/R/checkAtomic.R0000644000176200001440000000275114531605563014751 0ustar liggesusers#' Check that an argument is an atomic vector #' #' @description #' For the definition of \dQuote{atomic}, see \code{\link[base]{is.atomic}}. #' #' Note that `NULL` is recognized as a valid atomic value, as in R versions up to version 4.3.x. #' For details, see \url{https://stat.ethz.ch/pipermail/r-devel/2023-September/082892.html}. #' #' @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", use.namespace = FALSE) #' @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", use.namespace = FALSE) checkmate/R/checkEnvironment.R0000644000176200001440000000321514245411067016031 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, use.namespace = FALSE) #' @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, use.namespace = FALSE) checkmate/vignettes/0000755000176200001440000000000014651660101014206 5ustar liggesuserscheckmate/vignettes/tinytest.Rmd0000644000176200001440000000221114245411067016535 0ustar liggesusers--- title: "Setup tinytest" author: "Michel Lang" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Setup tinytest} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ## Setup `tinytest` Setting up the `tinytest` framework is covered in detail in the documentation of [tinytest](https://cran.r-project.org/package=tinytest). Quick summary: 1. In the package root directory, call `tinytest::setup_tinytest(".")`. 2. Edit/add R scripts with unit tests to the directory `inst/tinytest`. ## Setup `checkmate` 1. Edit your `DESCRIPTION` and add `checkmate` to `Suggests` unless it is already listed in `Imports` for its assertions. 2. In **each** test file which calls an expectation from `checkmate`, you must include the following lines at the beginning of the file: ```{r,eval=FALSE} library("tinytest") library("checkmate") using("checkmate") ``` If you forget the last line, expectations will not get reported correctly in the summary. Also note that sourcing a file which includes `using("checkmate")` is **not** sufficient. 3. Check if everything works with `R CMD check`. checkmate/vignettes/checkmate.Rmd0000644000176200001440000003107214245411067016605 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 these 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,fig.width=6,fig.height=4,dependson="init",eval=requireNamespace("microbenchmark", quietly = TRUE)} library(checkmate) 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,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,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: Test that `x` is a data frame with no missing values ```{r,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) ``` ### Benchmark 5: Assert that `x` is an increasing sequence of integers with no missing values ```{r,fig.width=6,fig.height=4,eval=requireNamespace("microbenchmark", quietly = TRUE)} N = 10000 x.altrep = seq_len(N) # this is an ALTREP in R version >= 3.5.0 x.sexp = c(x.altrep) # this is a regular SEXP OTOH r = function(x) stopifnot(is.integer(x), !any(is.na(x)), !is.unsorted(x)) cm = function(x) assertInteger(x, any.missing = FALSE, sorted = TRUE) mb = microbenchmark(r(x.sexp), cm(x.sexp), r(x.altrep), cm(x.altrep)) 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. ```{r, eval = FALSE, hilang = "c"} 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](https://r-pkgs.org/src.html#c-export) 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 below. 3. Include the provided header file `` in each compilation unit where you want to use checkmate. File contents for (2): ```{r, eval = FALSE, hilang = "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/src/0000755000176200001440000000000014651660101012765 5ustar liggesuserscheckmate/src/checks.c0000644000176200001440000007644314646750224014421 0ustar liggesusers#include #include #include #include "backports.h" #include "checks.h" #include "integerish.h" #include "is_sorted.h" #include "any_missing.h" #include "any_infinite.h" #include "all_missing.h" #include "find_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 (as_flag((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, as_flag(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 (as_flag((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 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); out[255] = '\0'; UNPROTECT(2); } static Rboolean check_bounds(SEXP x, SEXP lower, SEXP upper) { double tmp = as_number(lower, "lower"); if (R_FINITE(tmp) || tmp == R_PosInf) { const R_xlen_t n = xlength(x); if (isReal(x)) { const double *xp = REAL_RO(x); for (R_xlen_t i = 0; i < n; i++) { if (!ISNAN(xp[i]) && xp[i] < tmp) return message("Element %i is not >= %g", i + 1, tmp); } } else if (isInteger(x)) { const int *xp = INTEGER_RO(x); for (R_xlen_t i = 0; i < n; i++) { if (xp[i] != NA_INTEGER && xp[i] < tmp) return message("Element %i is not >= %g", i + 1, tmp); } } } tmp = as_number(upper, "upper"); if (R_FINITE(tmp) || tmp == R_NegInf) { const R_xlen_t n = xlength(x); if (isReal(x)) { const double *xp = REAL_RO(x); for (R_xlen_t i = 0; i < n; i++) { if (!ISNAN(xp[i]) && xp[i] > tmp) return message("Element %i is not <= %g", i + 1, tmp); } } else if (isInteger(x)) { const int *xp = INTEGER_RO(x); for (R_xlen_t i = 0; i < n; i++) { if (xp[i] != NA_INTEGER && xp[i] > tmp) return message("Element %i is not <= %g", i + 1, tmp); } } } return TRUE; } static Rboolean check_posix_bounds(SEXP x, SEXP lower, SEXP upper) { if (isNull(lower) && isNull(upper)) return TRUE; SEXP tz = PROTECT(getAttrib(x, install("tzone"))); R_len_t NPROTECT = 1; const Rboolean null_tz = isNull(tz); double *xp; if (isInteger(x)) { SEXP xr = PROTECT(coerceVector(x, REALSXP)); NPROTECT++; xp = REAL(xr); } else { xp = REAL(x); } if (!isNull(lower)) { if (!is_class_posixct(lower) || length(lower) != 1) error("Argument 'lower' must be provided as single POSIXct time"); SEXP lower_tz = PROTECT(getAttrib(lower, install("tzone"))); NPROTECT++; 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(NPROTECT); return message("Timezones of 'x' and 'lower' must match"); } const double tmp = isInteger(lower) ? (double) INTEGER_RO(lower)[0] : REAL_RO(lower)[0]; const R_xlen_t n = length(x); for (R_xlen_t i = 0; i < n; i++) { if (!ISNAN(xp[i]) && xp[i] < tmp) { char fmt[256]; fmt_posixct(fmt, lower); UNPROTECT(NPROTECT); return message("Element %i is not >= %s", i + 1, fmt); } } } if (!isNull(upper)) { if (!is_class_posixct(upper) || length(upper) != 1) error("Argument 'upper' must be provided as single POSIXct time"); SEXP upper_tz = PROTECT(getAttrib(upper, install("tzone"))); NPROTECT++; 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(NPROTECT); return message("Timezones of 'x' and 'upper' must match"); } const double tmp = isInteger(upper) ? (double) INTEGER_RO(upper)[0] : REAL_RO(upper)[0]; const R_xlen_t n = length(x); for (R_xlen_t i = 0; i < n; i++) { if (!ISNAN(xp[i]) && xp[i] > tmp) { char fmt[256]; fmt_posixct(fmt, upper); UNPROTECT(NPROTECT); return message("Element %i is not <= %s", i + 1, fmt); } } } UNPROTECT(NPROTECT); return TRUE; } static R_xlen_t 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 i + 1; for (; *str != '\0'; str++) { if (!isalnum(*str) && *str != '.' && *str != '_') return i + 1; } } return 0; } static Rboolean check_names(SEXP nn, const char * type, const char * what) { typedef enum { T_UNNAMED, T_NAMED, T_UNIQUE, T_STRICT, T_IDS } name_t; name_t checks = T_UNNAMED; if (strcmp(type, "unnamed") == 0) return isNull(nn) ? TRUE : message("May not have %s", 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 if (strcmp(type, "ids") == 0) { checks = T_IDS; } else { error("Unknown type '%s' to specify check for names. Supported are 'unnamed', 'named', 'unique' and 'strict'.", type); } if (isNull(nn)) { return message("Must have %s", what); } R_xlen_t pos = find_missing_string(nn); if (pos > 0) { return message("Must have %s, but is NA at position %i", what, pos); } pos = find_min_nchar(nn, 1); if (pos > 0) { return message("Must have %s, but element %i is empty", what, pos); } if (checks == T_UNIQUE || checks == T_STRICT) { pos = any_duplicated(nn, FALSE); if (pos > 0) return message("Must have unique %s, but element %i is duplicated", what, pos); } if (checks == T_STRICT || checks == T_IDS) { pos = check_strict_names(nn); if (pos > 0) return message("Must have %s according to R's variable naming conventions, but element %i does not comply", what, pos); } 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 = as_length(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 = as_length(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 = as_length(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 (!as_flag(any_missing, "any.missing")) { R_xlen_t pos = find_missing_vector(x); if (pos > 0) return message("Contains missing values (element %i)", pos); } if (!as_flag(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 (as_flag(unique, "unique")) { R_xlen_t pos = any_duplicated(x, FALSE); if (pos > 0) return message("Contains duplicated values, position %i", pos); } return TRUE; } static Rboolean check_vector_names(SEXP x, SEXP names) { if (!isNull(names) && xlength(x) > 0) return check_named(x, as_string(names, "names"), "names"); return TRUE; } static Rboolean check_vector_finite(SEXP x, SEXP finite) { // FIXME: pos if (as_flag(finite, "finite") && any_infinite(x)) return message("Must be finite"); return TRUE; } static Rboolean check_matrix_dims(SEXP x, SEXP min_rows, SEXP max_rows, SEXP min_cols, SEXP max_cols, SEXP rows, SEXP cols) { if (!isNull(min_rows) || !isNull(max_rows) || !isNull(rows)) { R_len_t xrows = get_nrows(x); if (!isNull(min_rows)) { R_len_t cmp = as_length(min_rows, "min.rows"); if (xrows < cmp) return message("Must have at least %i rows, but has %i rows", cmp, xrows); } if (!isNull(max_rows)) { R_len_t cmp = as_length(max_rows, "max.rows"); if (xrows > cmp) return message("Must have at most %i rows, but has %i rows", cmp, xrows); } if (!isNull(rows)) { R_len_t cmp = as_length(rows, "rows"); if (xrows != cmp) return message("Must have exactly %i rows, but has %i rows", cmp, xrows); } } if (!isNull(min_cols) || !isNull(max_cols) || !isNull(cols)) { R_len_t xcols = get_ncols(x); if (!isNull(min_cols)) { R_len_t cmp = as_length(min_cols, "min.cols"); if (xcols < cmp) return message("Must have at least %i cols, but has %i cols", cmp, xcols); } if (!isNull(max_cols)) { R_len_t cmp = as_length(max_cols, "max.cols"); if (xcols > cmp) return message("Must have at most %i cols, but has %i cols", cmp, xcols); } if (!isNull(cols)) { R_len_t cmp = as_count(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) && !all_missing(x)) { const char * const storage = as_string(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 (!is_class_numeric(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 (!is_class_list(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_RO(x)[0] == NA_LOGICAL); case INTSXP: return (INTEGER_RO(x)[0] == NA_INTEGER); case REALSXP: return ISNAN(REAL_RO(x)[0]); case STRSXP: return (STRING_ELT(x, 0) == NA_STRING); } } return FALSE; } static Rboolean check_vector_sorted(SEXP x, SEXP sorted) { if (as_flag(sorted, "sorted") && xlength(x) > 1) { if (!is_sorted(x)) { return message("Must be sorted"); } } return TRUE; } static Rboolean check_typed_missing(SEXP x, SEXP typed_missing) { if (as_flag(typed_missing, "typed.missing")) { return FALSE; } return TYPEOF(x) != VECSXP && all_missing_atomic(x); } static Rboolean check_string_nchar(SEXP x, SEXP n_chars, SEXP min_chars, SEXP max_chars) { if (!isNull(n_chars)) { R_xlen_t n = as_count(n_chars, "n.chars"); R_xlen_t pos = find_nchar(x, n); if (pos > 0) { return message("All elements must have exactly %i characters, but element %i has %i chararacters", n, pos, length(STRING_ELT(x, pos - 1))); } } if (!isNull(min_chars)) { R_xlen_t n = as_count(min_chars, "min.chars"); R_xlen_t pos = find_min_nchar(x, n); if (pos > 0) { return message("All elements must have at least %i characters, but element %i has %i characters", n, pos, length(STRING_ELT(x, pos - 1))); } } if (!isNull(max_chars)) { R_xlen_t n = as_count(max_chars, "max.chars"); R_xlen_t pos = find_max_nchar(x, n); if (pos > 0) { return message("All elements must have at most %i characters, but element %i has %i characters", n, pos, length(STRING_ELT(x, pos - 1))); } } return TRUE; } /*********************************************************************************************************************/ /* Exported check functions */ /*********************************************************************************************************************/ 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 typed_missing, SEXP null_ok) { HANDLE_TYPE_NULL(is_class_logical(x) || check_typed_missing(x, typed_missing), "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_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 typed_missing, SEXP null_ok) { HANDLE_TYPE_NULL(is_class_integer(x) || check_typed_missing(x, typed_missing), "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 typed_missing, SEXP null_ok) { double dtol = as_number(tol, "tol"); if (isNull((x))) { if (as_flag((null_ok), "null.ok")) return ScalarLogical(TRUE); snprintf(msg, 255, "Must be of type 'integerish', not 'NULL'"); return ScalarString(mkChar(msg)); } else { cm_int_err_t ok = checkIntegerish(x, dtol, FALSE); switch(ok.err) { case INT_OK: break; case INT_TYPE: if (!check_typed_missing(x, typed_missing)) { snprintf(msg, 255, "Must be of type 'integerish'%s, not '%s'", as_flag(null_ok, "null_ok") ? " (or 'NULL')" : "", guess_type(x)); return ScalarString(mkChar(msg)); } break; case INT_RANGE: snprintf(msg, 255, "Must be of type 'integerish', but element %g is not in integer range", (double)ok.pos); return ScalarString(mkChar(msg)); break; case INT_TOL: snprintf(msg, 255, "Must be of type 'integerish', but element %g is not close to an integer", (double)ok.pos); return ScalarString(mkChar(msg)); break; case INT_COMPLEX: snprintf(msg, 255, "Must be of type 'integerish', but element %g has an imaginary part", (double)ok.pos); return ScalarString(mkChar(msg)); break; } } 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_double(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 typed_missing, SEXP null_ok) { HANDLE_TYPE_NULL(is_class_double(x) || check_typed_missing(x, typed_missing), "double", 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_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 typed_missing, SEXP null_ok) { HANDLE_TYPE_NULL(is_class_numeric(x) || check_typed_missing(x, typed_missing), "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_character(SEXP x, SEXP n_chars, SEXP min_chars, SEXP max_chars, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP sorted, SEXP names, SEXP typed_missing, SEXP null_ok) { HANDLE_TYPE_NULL(is_class_string(x) || check_typed_missing(x, typed_missing), "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)); ASSERT_TRUE(check_string_nchar(x, n_chars, min_chars, max_chars)); ASSERT_TRUE(check_vector_unique(x, unique)); ASSERT_TRUE(check_vector_sorted(x, sorted)); 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 typed_missing, SEXP null_ok) { HANDLE_TYPE_NULL(is_class_complex(x) || check_typed_missing(x, typed_missing), "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 max_rows, SEXP min_cols, SEXP max_cols, SEXP rows, SEXP cols, SEXP row_names, SEXP col_names, SEXP null_ok) { HANDLE_TYPE_NULL(is_class_frame(x), "data.frame", null_ok); ASSERT_TRUE(check_matrix_dims(x, min_rows, max_rows, min_cols, max_cols, rows, cols)); if (!isNull(row_names)) { SEXP nn = PROTECT(getAttrib(x, install("row.names"))); int nprotect = 1; if (isInteger(nn)) { nn = PROTECT(coerceVector(nn, STRSXP)); nprotect++; } ASSERT_TRUE_UNPROTECT(check_names(nn, as_string(row_names, "row.names"), "rownames"), nprotect); } if (!isNull(col_names)) { ASSERT_TRUE(check_named(x, as_string(col_names, "col.names"), "colnames")); } if (!as_flag(any_missing, "any.missing")) { R_xlen_t pos = find_missing_frame(x); if (pos > 0) { R_xlen_t nrow = get_nrows(x); const char * nn = CHAR(STRING_ELT(getAttrib(x, R_NamesSymbol), translate_col(pos, nrow))); return result("Contains missing values (column '%s', row %i)", nn, translate_row(pos, nrow) + 1); } } if (!as_flag(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(is_class_factor(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_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(is_class_list(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_matrix(SEXP x, SEXP mode, SEXP any_missing, SEXP all_missing, SEXP min_rows, SEXP max_rows, SEXP min_cols, SEXP max_cols, SEXP rows, SEXP cols, SEXP row_names, SEXP col_names, SEXP null_ok) { HANDLE_TYPE_NULL(is_class_matrix(x), "matrix", null_ok); ASSERT_TRUE(check_storage(x, mode)); ASSERT_TRUE(check_matrix_dims(x, min_rows, max_rows, min_cols, max_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, as_string(row_names, "row.names"), "rownames"), 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, as_string(col_names, "col.names"), "colnames"), 1); } if (!as_flag(any_missing, "any.missing")) { R_xlen_t pos = find_missing_matrix(x); if (pos > 0) { R_xlen_t nrow = get_nrows(x); return result("Contains missing values (row %i, col %i)", translate_row(pos, nrow) + 1, translate_col(pos, nrow) + 1); } } if (!as_flag(all_missing, "all.missing") && all_missing_atomic(x)) { return result("Contains only missing values"); } 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(is_class_array(x), "array", null_ok); ASSERT_TRUE(check_storage(x, mode)); if (!as_flag(any_missing, "any.missing") && find_missing_vector(x) > 0) return result("Contains missing values"); R_len_t ndim = length(getAttrib(x, R_DimSymbol)); if (!isNull(d)) { R_len_t di = as_count(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 = as_count(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 = as_count(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, as_string(type, "type"), "Object")); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_names(SEXP x, SEXP type, SEXP what) { if (!(isString(x) || isNull(x))) return result("Must be a character vector"); ASSERT_TRUE(check_names(x, as_string(type, "type"), as_string(what, "what"))); 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 (as_flag(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_raw(SEXP x, SEXP len, SEXP min_len, SEXP max_len, SEXP names, SEXP null_ok) { HANDLE_TYPE_NULL(is_class_raw(x), "raw", null_ok); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); 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(is_class_atomic(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(is_class_atomic_vector(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 = as_number(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) as_flag(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 = as_number(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(is_class_numeric(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 n_chars, SEXP min_chars, SEXP max_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"); ASSERT_TRUE(check_string_nchar(x, n_chars, min_chars, max_chars)); 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_class_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/guess_type.c0000644000176200001440000000202414245411067015322 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, 511); buf[511] = '\0'; 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/any_nan.c0000644000176200001440000000203014247174202014552 0ustar liggesusers#include "any_nan.h" #include "backports.h" static Rboolean any_nan_double(SEXP x) { const double * xp = REAL_RO(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_RO(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.h0000644000176200001440000000033414245411067015616 0ustar liggesusers#ifndef CHECKMATE_ANY_INFINITE_H_ #define CHECKMATE_ANY_INFINITE_H_ #include #include #include Rboolean any_infinite(SEXP); SEXP attribute_hidden c_any_infinite(SEXP); #endif checkmate/src/init.c0000644000176200001440000001222414264222022014071 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, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_complex(SEXP, 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, 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, SEXP); extern SEXP c_check_integerish(SEXP, 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, SEXP); extern SEXP c_check_matrix(SEXP, SEXP, 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, 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, SEXP); extern SEXP c_check_double(SEXP, 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, SEXP, SEXP); extern SEXP c_check_vector(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_raw(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, 14}, {"c_check_complex", (DL_FUNC) &c_check_complex, 10}, {"c_check_count", (DL_FUNC) &c_check_count, 5}, {"c_check_dataframe", (DL_FUNC) &c_check_dataframe, 12}, {"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, 13}, {"c_check_integerish", (DL_FUNC) &c_check_integerish, 14}, {"c_check_list", (DL_FUNC) &c_check_list, 9}, {"c_check_logical", (DL_FUNC) &c_check_logical, 10}, {"c_check_matrix", (DL_FUNC) &c_check_matrix, 13}, {"c_check_named", (DL_FUNC) &c_check_named, 2}, {"c_check_names", (DL_FUNC) &c_check_names, 3}, {"c_check_number", (DL_FUNC) &c_check_number, 6}, {"c_check_numeric", (DL_FUNC) &c_check_numeric, 14}, {"c_check_double", (DL_FUNC) &c_check_double, 14}, {"c_check_scalar", (DL_FUNC) &c_check_scalar, 3}, {"c_check_string", (DL_FUNC) &c_check_string, 6}, {"c_check_vector", (DL_FUNC) &c_check_vector, 10}, {"c_check_raw", (DL_FUNC) &c_check_raw, 6}, {"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/find_nchar.h0000644000176200001440000000035014646750234015242 0ustar liggesusers#ifndef CHECKMATE_FIND_NCHAR_H_ #define CHECKMATE_FIND_NCHAR_H_ #include #include R_xlen_t find_nchar(SEXP, R_xlen_t); R_xlen_t find_min_nchar(SEXP, R_xlen_t); R_xlen_t find_max_nchar(SEXP, R_xlen_t); #endif checkmate/src/any_infinite.c0000644000176200001440000000224514247412116015612 0ustar liggesusers#include "any_infinite.h" #include "backports.h" static Rboolean any_infinite_double(SEXP x) { const double * xp = REAL_RO(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_RO(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/qassert.c0000644000176200001440000004722514245411067014631 0ustar liggesusers#include "qassert.h" #include "helper.h" #include "guess_type.h" #include "any_missing.h" #include "integerish.h" #include "backports.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_POSIX, CL_FUNCTION, CL_ENVIRONMENT, CL_NULL, CL_NONE } cm_class_t; static const char * CLSTR[] = { "logical", "integer", "integerish", "numeric", "double", "string", "factor", "list", "complex", "atomic", "atomic vector", "matrix", "data frame", "POSIXct", "function", "environment", "NULL" }; typedef enum { LT, LE, EQ, GE, GT, NE, NONE } cm_cmp_t; static const char * CMPSTR[] = { "<", "<=", "==", ">=", ">", "!=" }; typedef R_xlen_t(*cm_miss_fun_t)(SEXP); typedef Rboolean(*cm_dd_cmp)(double, double); typedef Rboolean(*cm_ll_cmp)(R_xlen_t, R_xlen_t); typedef struct { cm_dd_cmp fun; double cmp; cm_cmp_t op; } bound_t; typedef struct { struct { Rboolean(*fun)(SEXP); cm_class_t name; } class; cm_miss_fun_t missing_fun; struct { cm_ll_cmp fun; R_xlen_t cmp; cm_cmp_t op; } len; bound_t lower; bound_t upper; } cm_checker_t; typedef struct { Rboolean ok; char msg[255]; } cm_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 cm_msg_t MSGT = { .ok = TRUE }; static cm_msg_t MSGF = { .ok = FALSE }; static cm_msg_t message(const char *fmt, ...) { cm_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 cm_msg_t check_bound(SEXP x, const bound_t bound) { if (isReal(x)) { const double *xp = REAL_RO(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_RO(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(cm_checker_t *checker, const char *rule) { checker->missing_fun = NULL; switch(rule[0]) { case 'B': checker->missing_fun = &find_missing_logical; case 'b': checker->class.fun = &is_class_logical; checker->class.name = CL_LOGICAL; break; case 'I': checker->missing_fun = &find_missing_integer; case 'i': checker->class.fun = &is_class_integer; checker->class.name = CL_INTEGER; break; case 'X': checker->missing_fun = &find_missing_integerish; case 'x': checker->class.fun = &is_class_integerish; checker->class.name = CL_INTEGERISH; break; case 'N': checker->missing_fun = &find_missing_numeric; case 'n': checker->class.fun = &is_class_numeric; checker->class.name = CL_NUMERIC; break; case 'R': checker->missing_fun = &find_missing_double; case 'r': checker->class.fun = &is_class_double; checker->class.name = CL_DOUBLE; break; case 'S': checker->missing_fun = &find_missing_string; case 's': checker->class.fun = &is_class_string; checker->class.name = CL_STRING; break; case 'F': checker->missing_fun = &find_missing_integer; case 'f': checker->class.fun = &is_class_factor; checker->class.name = CL_FACTOR; break; case 'L': checker->missing_fun = &find_missing_list; case 'l': checker->class.fun = &is_class_list; checker->class.name = CL_LIST; break; case 'C': checker->missing_fun = &find_missing_complex; case 'c': checker->class.fun = &is_class_complex; checker->class.name = CL_COMPLEX; break; case 'A': checker->missing_fun = &find_missing_vector; case 'a': checker->class.fun = &is_class_atomic; checker->class.name = CL_ATOMIC; break; case 'V': checker->missing_fun = &find_missing_vector; case 'v': checker->class.fun = &is_class_atomic_vector; checker->class.name = CL_ATOMIC_VECTOR; break; case 'M': checker->missing_fun = &find_missing_matrix; case 'm': checker->class.fun = &is_class_matrix; checker->class.name = CL_MATRIX; break; case 'D': checker->missing_fun = &find_missing_frame; case 'd': checker->class.fun = &is_class_frame; checker->class.name = CL_DATAFRAME; break; case 'P': checker->missing_fun = &find_missing_numeric; case 'p': checker->class.fun = &is_class_posixct; checker->class.name = CL_POSIX; 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(cm_checker_t *checker, const char *rule) { checker->len.fun = NULL; checker->len.op = NONE; checker->len.cmp = 0; switch(rule[0]) { case '\0': return 0; case '*': 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 '[': 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 = LT; 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(cm_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(cm_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 cm_msg_t check_rule(SEXP x, const cm_checker_t *checker, 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) { R_xlen_t pos = checker->missing_fun(x); if (pos > 0) { if (is_class_matrix(x)) { R_len_t nrow = get_nrows(x); return err_msg ? message("May not contain missing values, first at column %i, element %i", translate_col(pos, nrow) + 1, translate_row(pos, nrow) + 1) : MSGF; } if (is_class_frame(x)) { R_len_t nrow = get_nrows(x); const char * nn = CHAR(STRING_ELT(getAttrib(x, R_NamesSymbol), translate_col(pos, nrow))); return err_msg ? message("May not contain missing values, first at column '%s', element %i", nn, translate_row(pos, nrow) + 1) : MSGF; } return err_msg ? message("May not contain missing values, first at position %i", pos) : 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) { cm_msg_t msg = check_bound(x, checker->lower); if (!msg.ok) return msg; } if (checker->upper.fun != NULL) { cm_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 cm_checker_t *checker, cm_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 cm_checker_t *checker, cm_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) { cm_checker_t checker; parse_rule(&checker, rule); cm_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 R_len_t nrules = length(rules); R_len_t failed; if (!isString(rules)) error("Argument 'rules' must be a string"); if (nrules == 0) return ScalarLogical(TRUE); cm_msg_t result[nrules]; cm_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_RO(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 cm_checker_t *checker, const R_len_t nrules) { cm_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 cm_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 (is_class_list(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) { cm_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); cm_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_RO(recursive)[0]) { return ScalarLogical(qtest_list(x, checker, nrules, as_count(depth, "depth"))); } return ScalarLogical(qtest1(x, checker, nrules)); } /*********************************************************************************************************************/ /* qcheck stuff */ /*********************************************************************************************************************/ /* exported for other packages */ SEXP qcheck(SEXP x, const char *rule, const char *name) { cm_checker_t checker; parse_rule(&checker, rule); cm_msg_t result = check_rule(x, &checker, TRUE); if (!result.ok) { char msg[512]; snprintf(msg, 512, "Variable '%s': %s", name, result.msg); return ScalarString(mkChar(msg)); } return ScalarLogical(TRUE); } checkmate/src/find_nchar.c0000644000176200001440000000203714646750230015235 0ustar liggesusers#include "find_nchar.h" typedef Rboolean(*cm_ll_cmp)(R_xlen_t, R_xlen_t); static inline Rboolean ii_eq(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 R_xlen_t check_nchar(SEXP x, R_xlen_t n, cm_ll_cmp cmp) { if (!isString(x)) { SEXP xs = PROTECT(coerceVector(x, STRSXP)); R_xlen_t res = check_nchar(xs, n, cmp); UNPROTECT(1); return res; } const R_xlen_t nx = xlength(x); for (R_xlen_t i = 0; i < nx; i++) { SEXP tmp = STRING_ELT(x, i); if (tmp != NA_STRING && !(*cmp)(length(tmp), n)) { return i + 1; } } return 0; } R_xlen_t find_nchar(SEXP x, R_xlen_t n) { return check_nchar(x, n, &ii_eq); } R_xlen_t find_min_nchar(SEXP x, R_xlen_t n) { return check_nchar(x, n, &ii_ge); } R_xlen_t find_max_nchar(SEXP x, R_xlen_t n) { return check_nchar(x, n, &ii_le); } checkmate/src/checks.h0000644000176200001440000000424614264222022014400 0ustar liggesusers#ifndef CHECKMATE_CHECKS_H_ #define CHECKMATE_CHECKS_H_ #include #include #include SEXP attribute_hidden c_check_logical(SEXP, 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); SEXP attribute_hidden c_check_integerish(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_double(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_numeric(SEXP, SEXP, SEXP, SEXP, 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); SEXP attribute_hidden c_check_character(SEXP, SEXP, SEXP, SEXP, 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_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_dataframe(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_matrix(SEXP, SEXP, 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); 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, SEXP, SEXP); #endif checkmate/src/helper.c0000644000176200001440000001223014645726235014424 0ustar liggesusers#include #include "helper.h" #include "any_missing.h" #include "integerish.h" #include "guess_type.h" #include "backports.h" R_len_t translate_row(R_len_t pos, R_len_t nrow) { return (pos - 1) % nrow; } R_len_t translate_col(R_len_t pos, R_len_t nrow) { return (R_len_t)((pos - 1) / nrow); } /* 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)) { if (inherits(x, "data.table")) { /* c.f. https://github.com/Rdatatable/data.table/issues/3149 */ return (length(x) == 0) ? 0 : length(VECTOR_ELT(x, 0)); } else { return length(getAttrib(x, R_RowNamesSymbol)); } } SEXP dim = getAttrib(x, R_DimSymbol); return (dim == R_NilValue) ? length(x) : INTEGER_RO(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_RO(dim)[1] : 1; } double attribute_hidden as_number(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 %g", vname, (double)xlength(x)); double xd = asReal(x); if (ISNAN(xd)) error("Argument '%s' may not be missing", vname); return xd; } const char attribute_hidden * as_string(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 (find_missing_string(x) > 0) error("Argument '%s' may not be missing", vname); return CHAR(STRING_ELT(x, 0)); } R_len_t attribute_hidden as_count(SEXP x, const char *vname) { if (length(x) != 1) error("Argument '%s' 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 as_length(SEXP x, const char *vname) { if (length(x) != 1) error("Argument '%s' must have length 1", vname); switch(TYPEOF(x)) { case INTSXP:; int xi = INTEGER_RO(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_RO(x)[0]; if (ISNA(xr)) 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 as_flag(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_RO(x)[0]; if (xb == NA_LOGICAL) error("Argument '%s' may not be missing", vname); return xb; } Rboolean is_class_logical(SEXP x) { return isLogical(x); } Rboolean is_class_integer(SEXP x) { return isInteger(x); } Rboolean is_class_integerish(SEXP x) { return isIntegerish(x, INTEGERISH_DEFAULT_TOL, TRUE); } Rboolean is_class_numeric(SEXP x) { switch(TYPEOF(x)) { case REALSXP: return TRUE; case INTSXP: return !inherits(x, "factor"); } return FALSE; } Rboolean is_class_double(SEXP x) { return isReal(x); } Rboolean is_class_complex(SEXP x) { return isComplex(x); } Rboolean is_class_string(SEXP x) { return isString(x); } Rboolean is_class_factor(SEXP x) { return isFactor(x); } Rboolean is_class_atomic(SEXP x) { return isNull(x) || isVectorAtomic(x); } Rboolean is_class_atomic_vector(SEXP x) { if (!isVectorAtomic(x)) return FALSE; return isNull(getAttrib(x, R_DimSymbol)); } Rboolean is_class_list(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; } Rboolean is_class_matrix(SEXP x) { return isMatrix(x); } Rboolean is_class_array(SEXP x) { return isArray(x); } Rboolean is_class_frame(SEXP x) { return isFrame(x); } Rboolean is_class_environment(SEXP x) { return isEnvironment(x); } Rboolean is_class_null(SEXP x) { return isNull(x); } Rboolean is_class_posixct(SEXP x) { return isNumeric(x) && inherits(x, "POSIXct"); } Rboolean is_class_raw(SEXP x) { return TYPEOF(x) == RAWSXP; } checkmate/src/all_missing.c0000644000176200001440000000640514245411067015443 0ustar liggesusers#include "all_missing.h" #include "backports.h" Rboolean attribute_hidden all_missing_logical(SEXP x) { #if defined(R_VERSION) && R_VERSION >= R_Version(3, 6, 0) if (LOGICAL_NO_NA(x)) return FALSE; #endif const int * xp = LOGICAL_RO(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) { #if defined(R_VERSION) && R_VERSION >= R_Version(3, 5, 0) if (INTEGER_NO_NA(x)) return FALSE; #endif const int * xp = INTEGER_RO(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) { #if defined(R_VERSION) && R_VERSION >= R_Version(3, 5, 0) if (REAL_NO_NA(x)) return FALSE; #endif const double * xp = REAL_RO(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_RO(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) { #if defined(R_VERSION) && R_VERSION >= R_Version(3, 5, 0) if (STRING_NO_NA(x)) return FALSE; #endif 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); case VECSXP: return all_missing_list(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++) { SEXP xi = VECTOR_ELT(x, i); if (TYPEOF(xi) != VECSXP && all_missing_atomic(xi)) 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/integerish.h0000644000176200001440000000101014245411067015273 0ustar liggesusers#ifndef CHECKMATE_INTEGERISH_H_ #define CHECKMATE_INTEGERISH_H_ #include #include #include #include #define INTEGERISH_DEFAULT_TOL sqrt(DBL_EPSILON) typedef enum { INT_OK, INT_TYPE, INT_RANGE, INT_TOL, INT_COMPLEX } cm_int_check_t; typedef struct { R_xlen_t pos; cm_int_check_t err; } cm_int_err_t; Rboolean isIntegerish(SEXP, double, Rboolean); SEXP attribute_hidden c_is_integerish(SEXP, SEXP); cm_int_err_t checkIntegerish(SEXP, const double, Rboolean); #endif checkmate/src/is_sorted.c0000644000176200001440000000404714645726235015147 0ustar liggesusers#include "is_sorted.h" #include "backports.h" static Rboolean is_sorted_integer(SEXP x) { #if defined(R_VERSION) && R_VERSION >= R_Version(3, 5, 0) int sorted = INTEGER_IS_SORTED(x); if (sorted != UNKNOWN_SORTEDNESS) return KNOWN_INCR(sorted); #endif R_xlen_t i = 0; const R_xlen_t n = xlength(x); const int * const xi = INTEGER_RO(x); while(i < n && xi[i] == NA_INTEGER) i++; 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) { #if defined(R_VERSION) && R_VERSION >= R_Version(3, 5, 0) int sorted = REAL_IS_SORTED(x); if (sorted != UNKNOWN_SORTEDNESS) return KNOWN_INCR(sorted); #endif R_xlen_t i = 0; const R_xlen_t n = xlength(x); const double * const xr = REAL_RO(x); while(i < n && ISNA(xr[i])) i++; for (R_xlen_t j = i + 1; j < n; j++) { if (!ISNA(xr[j])) { if (xr[i] > xr[j]) return FALSE; i = j; } } return TRUE; } static Rboolean is_sorted_character(SEXP x) { #if defined(R_VERSION) && R_VERSION >= R_Version(3, 5, 0) int sorted = STRING_IS_SORTED(x); if (sorted != UNKNOWN_SORTEDNESS) return KNOWN_INCR(sorted); #endif const R_xlen_t n = length(x); R_xlen_t i = 0; SEXP xi, xj; while(i < n) { xi = STRING_ELT(x, i); if (xi != NA_STRING) break; } for (R_xlen_t j = i + 1; j < n; j++) { xj = STRING_ELT(x, j); if (xj != NA_STRING) { if (strcmp(CHAR(xi), CHAR(xj)) > 0) return FALSE; xi = xj; } } return TRUE; } Rboolean is_sorted(SEXP x) { switch(TYPEOF(x)) { case INTSXP: return is_sorted_integer(x); case REALSXP: return is_sorted_double(x); case STRSXP: return is_sorted_character(x); default: error("Checking for sorted vector only possible for integer and double"); } } checkmate/src/guess_type.h0000644000176200001440000000033014245411067015325 0ustar liggesusers#ifndef CHECKMATE_GUESS_TYPE_H_ #define CHECKMATE_GUESS_TYPE_H_ #include #include #include const char * guess_type(SEXP); SEXP attribute_hidden c_guess_type(SEXP); #endif checkmate/src/all_missing.h0000644000176200001440000000114314245411067015442 0ustar liggesusers#ifndef CHECKMATE_ALL_MISSING_H_ #define CHECKMATE_ALL_MISSING_H_ #include #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/any_missing.c0000644000176200001440000001025314245411067015456 0ustar liggesusers#include "any_missing.h" #include "backports.h" R_xlen_t attribute_hidden find_missing_logical(SEXP x) { #if defined(R_VERSION) && R_VERSION >= R_Version(3, 6, 0) if (LOGICAL_NO_NA(x)) return 0; #endif const R_xlen_t n = xlength(x); const int * xp = LOGICAL_RO(x); for (R_xlen_t i = 0; i < n; i++) { if (xp[i] == NA_LOGICAL) return i + 1; } return 0; } R_xlen_t attribute_hidden find_missing_integer(SEXP x) { #if defined(R_VERSION) && R_VERSION >= R_Version(3, 5, 0) if (INTEGER_NO_NA(x)) return 0; #endif const R_xlen_t n = xlength(x); const int * xp = INTEGER_RO(x); for (R_xlen_t i = 0; i < n; i++) { if (xp[i] == NA_INTEGER) return i + 1; } return 0; } R_xlen_t attribute_hidden find_missing_integerish(SEXP x) { switch(TYPEOF(x)) { case LGLSXP: return find_missing_logical(x); case INTSXP: return find_missing_integer(x); case REALSXP: return find_missing_double(x); default: error("Error in find_missing_integerish: x must be logical or numeric"); } } R_xlen_t attribute_hidden find_missing_double(SEXP x) { #if defined(R_VERSION) && R_VERSION >= R_Version(3, 5, 0) if (REAL_NO_NA(x)) return 0; #endif const R_xlen_t n = xlength(x); const double * xp = REAL_RO(x); for (R_xlen_t i = 0; i < n; i++) { if (ISNAN(xp[i])) return i + 1; } return 0; } R_xlen_t attribute_hidden find_missing_numeric(SEXP x) { switch(TYPEOF(x)) { case INTSXP: return find_missing_integer(x); case REALSXP: return find_missing_double(x); default: error("Error in find_missing_numeric: x must be integer or double"); } } R_xlen_t attribute_hidden find_missing_complex(SEXP x) { const R_xlen_t n = xlength(x); const Rcomplex * xp = COMPLEX_RO(x); for (R_xlen_t i = 0; i < n; i++) { if (ISNAN((xp[i]).r) || ISNAN((xp[i]).i)) return i + 1; } return 0; } R_xlen_t attribute_hidden find_missing_string(SEXP x) { #if defined(R_VERSION) && R_VERSION >= R_Version(3, 5, 0) if (STRING_NO_NA(x)) return 0; #endif const R_xlen_t nx = xlength(x); for (R_xlen_t i = 0; i < nx; i++) { if (STRING_ELT(x, i) == NA_STRING) return i + 1; } return 0; } R_xlen_t attribute_hidden find_missing_list(SEXP x) { const R_xlen_t n = xlength(x); for (R_xlen_t i = 0; i < n; i++) { if (isNull(VECTOR_ELT(x, i))) return i + 1; } return 0; } R_xlen_t attribute_hidden find_missing_vector(SEXP x) { switch(TYPEOF(x)) { case LGLSXP: return find_missing_logical(x); case INTSXP: return find_missing_integer(x); case REALSXP: return find_missing_double(x); case CPLXSXP: return find_missing_complex(x); case STRSXP: return find_missing_string(x); case VECSXP: return find_missing_list(x); default: return 0; } } R_xlen_t attribute_hidden find_missing_matrix(SEXP x) { return find_missing_vector(x); } R_xlen_t attribute_hidden find_missing_frame(SEXP x) { const R_xlen_t nc = xlength(x); for (R_xlen_t j = 0; j < nc; j++) { SEXP xj = VECTOR_ELT(x, j); if (TYPEOF(xj) != VECSXP) { R_xlen_t i = find_missing_vector(xj); if (i > 0) { return (j * length(xj)) + i; } } } return 0; } Rboolean any_missing(SEXP x) { switch(TYPEOF(x)) { case LGLSXP: return find_missing_logical(x) > 0; case INTSXP: return find_missing_integer(x) > 0; case REALSXP: return find_missing_double(x) > 0; case CPLXSXP: return find_missing_complex(x) > 0; case STRSXP: return find_missing_string(x) > 0; case NILSXP: return FALSE; case VECSXP: if (isFrame(x)) { return find_missing_frame(x) > 0; } else { return find_missing_list(x) > 0; } 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/which_first.c0000644000176200001440000000272214245411067015451 0ustar liggesusers#include "which_first.h" #include "backports.h" static inline SEXP named_return(R_xlen_t ind, SEXP x, SEXP use_names) { if (!LOGICAL_RO(use_names)[0]) { return ScalarInteger(ind + 1); } SEXP names = PROTECT(getAttrib(x, R_NamesSymbol)); if (isNull(names)) { UNPROTECT(1); return ScalarInteger(ind + 1); } SEXP res = PROTECT(ScalarInteger(ind + 1)); setAttrib(res, R_NamesSymbol, ScalarString(STRING_ELT(names, ind))); UNPROTECT(2); 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); const int *xp = LOGICAL_RO(x); for (R_xlen_t i = 0; i < n; i++) { if (xp[i] != NA_LOGICAL && xp[i]) { return named_return(i, x, use_names); } } 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"); const int *xp = LOGICAL_RO(x); for (R_xlen_t i = xlength(x) - 1; i >= 0; i--) { if (xp[i] != NA_LOGICAL && xp[i]) { return named_return(i, x, use_names); } } return allocVector(INTSXP, 0); } checkmate/src/is_sorted.h0000644000176200001440000000024114245411067015132 0ustar liggesusers#ifndef CHECKMATE_IS_SORTED_H_ #define CHECKMATE_IS_SORTED_H_ #include #include #include Rboolean is_sorted(SEXP x); #endif checkmate/src/which_first.h0000644000176200001440000000032014245411067015446 0ustar liggesusers#ifndef CHECKMATE_WHICH_FIRST_H_ #define CHECKMATE_WHICH_FIRST_H_ #include #include #include SEXP c_which_first(SEXP, SEXP); SEXP c_which_last(SEXP, SEXP); #endif checkmate/src/any_missing.h0000644000176200001440000000147214245411067015466 0ustar liggesusers#ifndef CHECKMATE_ANY_MISSING_H_ #define CHECKMATE_ANY_MISSING_H_ #include #include #include #include R_xlen_t attribute_hidden find_missing_logical(SEXP); R_xlen_t attribute_hidden find_missing_integer(SEXP); R_xlen_t attribute_hidden find_missing_integerish(SEXP); R_xlen_t attribute_hidden find_missing_double(SEXP); R_xlen_t attribute_hidden find_missing_numeric(SEXP); R_xlen_t attribute_hidden find_missing_complex(SEXP); R_xlen_t attribute_hidden find_missing_string(SEXP); R_xlen_t attribute_hidden find_missing_vector(SEXP); R_xlen_t attribute_hidden find_missing_list(SEXP); R_xlen_t attribute_hidden find_missing_matrix(SEXP); R_xlen_t attribute_hidden find_missing_frame(SEXP); Rboolean any_missing(SEXP); SEXP attribute_hidden c_any_missing(SEXP); #endif checkmate/src/backports.h0000644000176200001440000000052614245411067015135 0ustar liggesusers#include #include #ifndef LOGICAL_RO #define LOGICAL_RO(x) ((const int *) LOGICAL(x)) #endif #ifndef INTEGER_RO #define INTEGER_RO(x) ((const int *) INTEGER(x)) #endif #ifndef REAL_RO #define REAL_RO(x) ((const double *) REAL(x)) #endif #ifndef COMPLEX_RO #define COMPLEX_RO(x) ((const Rcomplex *) COMPLEX(x)) #endif checkmate/src/any_nan.h0000644000176200001440000000031014245411067014557 0ustar liggesusers#ifndef CHECKMATE_ANY_NAN_H_ #define CHECKMATE_ANY_NAN_H_ #include #include #include Rboolean any_nan(SEXP); SEXP attribute_hidden c_any_nan(SEXP); #endif checkmate/src/qassert.h0000644000176200001440000000050714245411067014626 0ustar liggesusers#ifndef CHECKMATE_QASSERT_H_ #define CHECKMATE_QASSERT_H_ #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/src/integerish.c0000644000176200001440000000477614245411067015314 0ustar liggesusers#include #include #include "integerish.h" #include "backports.h" #include "all_missing.h" static inline cm_int_err_t check_convertible_logical(SEXP x, Rboolean logicals_ok) { cm_int_err_t res = { 0, (logicals_ok || all_missing_logical(x)) ? INT_OK : INT_TYPE }; return res; } static inline cm_int_check_t is_unconvertible_double(const double x, const double tol) { if (!ISNAN(x)) { if (x <= INT_MIN || x > INT_MAX) return INT_RANGE; if (fabs(x - nearbyint(x)) > tol) return INT_TOL; } return INT_OK; } static cm_int_err_t check_convertible_double(SEXP x, const double tol) { const double *xr = REAL_RO(x); const R_xlen_t n = length(x); cm_int_err_t res = { 0, INT_OK }; for (R_xlen_t i = 0; i < n; i++) { res.err = is_unconvertible_double(xr[i], tol); if (res.err != INT_OK) { res.pos = i + 1; break; } } return res; } static inline cm_int_check_t is_unconvertible_complex(Rcomplex x, const double tol) { if (!ISNAN(x.i) && fabs(x.i) > tol) return INT_COMPLEX; return is_unconvertible_double(x.r, tol); } static cm_int_err_t check_convertible_complex(SEXP x, const double tol) { const Rcomplex * xc = COMPLEX_RO(x); const R_xlen_t n = length(x); cm_int_err_t res = { 0, INT_OK }; for (R_xlen_t i = 0; i < n; i++) { cm_int_check_t ok = is_unconvertible_complex(xc[i], tol); if (ok != INT_OK) { res.pos = i + 1; res.err = ok; break; } } return res; } cm_int_err_t checkIntegerish(SEXP x, const double tol, Rboolean logicals_ok) { cm_int_err_t res = { 0, INT_OK}; switch(TYPEOF(x)) { case INTSXP: if (inherits(x, "factor")) res.err = INT_TYPE; break; case LGLSXP: res = check_convertible_logical(x, logicals_ok); break; case REALSXP: if (inherits(x, "Date") || inherits(x, "POSIXt")) { res.err = INT_TYPE; } else { res = check_convertible_double(x, tol); } break; case CPLXSXP: res = check_convertible_complex(x, tol); break; default: res.err = INT_TYPE; } return res; } Rboolean isIntegerish(SEXP x, const double tol, Rboolean logicals_ok) { cm_int_err_t res = checkIntegerish(x, tol, logicals_ok); return res.err == INT_OK; } SEXP attribute_hidden c_is_integerish(SEXP x, SEXP tolerance) { return ScalarLogical(isIntegerish(x, REAL_RO(tolerance)[0], FALSE)); } checkmate/src/helper.h0000644000176200001440000000227114245411067014423 0ustar liggesusers#ifndef CHECKMATE_HELPER_H_ #define CHECKMATE_HELPER_H_ #include #include #include R_len_t translate_row(R_len_t, R_len_t); R_len_t translate_col(R_len_t, R_len_t); R_len_t attribute_hidden get_ncols(SEXP); R_len_t attribute_hidden get_nrows(SEXP); double attribute_hidden as_number(SEXP, const char *); const char attribute_hidden * as_string(SEXP, const char *); R_len_t attribute_hidden as_count(SEXP, const char *); R_xlen_t attribute_hidden as_length(SEXP, const char *); Rboolean attribute_hidden as_flag(SEXP, const char *); Rboolean is_class_logical(SEXP x); Rboolean is_class_integer(SEXP x); Rboolean is_class_integerish(SEXP x); Rboolean is_class_double(SEXP x); Rboolean is_class_numeric(SEXP x); Rboolean is_class_complex(SEXP x); Rboolean is_class_string(SEXP x); Rboolean is_class_factor(SEXP x); Rboolean is_class_atomic(SEXP x); Rboolean is_class_atomic_vector(SEXP x); Rboolean is_class_list(SEXP x); Rboolean is_class_matrix(SEXP x); Rboolean is_class_array(SEXP x); Rboolean is_class_frame(SEXP x); Rboolean is_class_environment(SEXP x); Rboolean is_class_null(SEXP x); Rboolean is_class_posixct(SEXP x); Rboolean is_class_raw(SEXP x); #endif checkmate/NAMESPACE0000644000176200001440000002225514421735677013443 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(assertCharacter) export(assertChoice) export(assertClass) export(assertComplex) export(assertCount) export(assertDataFrame) export(assertDataTable) export(assertDate) export(assertDirectory) export(assertDirectoryExists) export(assertDisjunct) export(assertDouble) export(assertEnvironment) export(assertFALSE) export(assertFactor) export(assertFile) export(assertFileExists) export(assertFlag) export(assertFormula) export(assertFunction) export(assertInt) export(assertInteger) export(assertIntegerish) export(assertList) export(assertLogical) export(assertMatrix) export(assertMultiClass) export(assertNamed) export(assertNames) export(assertNull) export(assertNumber) export(assertNumeric) export(assertOS) export(assertPOSIXct) export(assertPathForOutput) export(assertPermutation) export(assertR6) export(assertRaw) 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_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_disjunct) export(assert_double) export(assert_environment) export(assert_factor) export(assert_false) export(assert_file) export(assert_file_exists) export(assert_flag) export(assert_formula) export(assert_function) export(assert_int) export(assert_integer) export(assert_integerish) export(assert_list) export(assert_logical) export(assert_matrix) export(assert_multi_class) 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_permutation) export(assert_posixct) export(assert_r6) export(assert_raw) 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(checkCharacter) export(checkChoice) export(checkClass) export(checkComplex) export(checkCount) export(checkDataFrame) export(checkDataTable) export(checkDate) export(checkDirectory) export(checkDirectoryExists) export(checkDisjunct) export(checkDouble) export(checkEnvironment) export(checkFALSE) export(checkFactor) export(checkFile) export(checkFileExists) export(checkFlag) export(checkFormula) export(checkFunction) export(checkInt) export(checkInteger) export(checkIntegerish) export(checkList) export(checkLogical) export(checkMatrix) export(checkMultiClass) export(checkNamed) export(checkNames) export(checkNull) export(checkNumber) export(checkNumeric) export(checkOS) export(checkPOSIXct) export(checkPathForOutput) export(checkPermutation) export(checkR6) export(checkRaw) 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_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_disjunct) export(check_double) export(check_environment) export(check_factor) export(check_false) export(check_file_exists) export(check_flag) export(check_formula) export(check_function) export(check_int) export(check_integer) export(check_integerish) export(check_list) export(check_logical) export(check_matrix) export(check_multi_class) 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_permutation) export(check_posixct) export(check_r6) export(check_raw) 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_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_disjunct) export(expect_double) export(expect_environment) export(expect_factor) export(expect_file) export(expect_file_exists) export(expect_flag) export(expect_formula) export(expect_function) export(expect_int) export(expect_integer) export(expect_integerish) export(expect_list) export(expect_logical) export(expect_matrix) export(expect_multi_class) export(expect_names) export(expect_number) export(expect_numeric) export(expect_os) export(expect_path_for_output) export(expect_permutation) export(expect_posixct) export(expect_r6) export(expect_raw) export(expect_scalar) export(expect_scalar_na) export(expect_set_equal) export(expect_string) export(expect_subset) export(expect_tibble) 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(register_test_backend) export(reportAssertions) export(testAccess) export(testArray) export(testAtomic) export(testAtomicVector) export(testCharacter) export(testChoice) export(testClass) export(testComplex) export(testCount) export(testDataFrame) export(testDataTable) export(testDate) export(testDirectory) export(testDirectoryExists) export(testDisjunct) export(testDouble) export(testEnvironment) export(testFALSE) export(testFactor) export(testFile) export(testFileExists) export(testFlag) export(testFormula) export(testFunction) export(testInt) export(testInteger) export(testIntegerish) export(testList) export(testLogical) export(testMatrix) export(testMultiClass) export(testNamed) export(testNames) export(testNull) export(testNumber) export(testNumeric) export(testOS) export(testPOSIXct) export(testPathForOutput) export(testPermutation) export(testR6) export(testRaw) 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_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_disjunct) export(test_double) export(test_environment) export(test_factor) export(test_false) export(test_file_exists) export(test_flag) export(test_formula) export(test_function) export(test_int) export(test_integer) export(test_integerish) export(test_list) export(test_logical) export(test_matrix) export(test_multi_class) 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_permutation) export(test_posixct) export(test_r6) export(test_raw) 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(stats,setNames) 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_double) 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_raw) 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/LICENSE0000644000176200001440000000011014531605563013203 0ustar liggesusersYEAR: 2023 COPYRIGHT HOLDER: Michel Lang ORGANIZATION: copyright holder checkmate/NEWS.md0000644000176200001440000003244314651660061013307 0ustar liggesusers# Version 2.3.2 * Removed calls to deprecated / internal C routines. * Fixed compiler warnings regarding sprintf format strings. * Fixed an issue regarding sortedness and missing numeric values (#259, thanks to @tdeenes) # Version 2.3.1 * Fixed a sprintf format string for long integers. # Version 2.3.0 * `NULL` is not longer considered to be atomic in future versions of R (c.f. ). To avoid breaking reverse dependencies, checkmate will stick to the old behavior until further notice. * Fixed a warning in `checkAtomic()` (#245). # Version 2.2.0 * Fixed C compiler warnings for windows * Added `checkPermutation` (#230). * Better handling of long vectors (#231). * Fixed a bounds check for numeric vectors and infinite bounds. # Version 2.1.0 * New arguments `n.chars` and `max.chars` for `checkCharacter()` and `checkString()`. * Checks for integerish now compare the tolerance with the difference to the nearest integer with `>` instead of `>=` to allow specifying a tolerance of exactly `0` (#177). * Checks for integerish now check for class `Date` an `POSIXt`. * Coercion of double to integer in `assertInt()` and `assertIntegerish()` now round to the nearest integer instead of always rounding via `trunc()`. * Fixed an error message where the wrong variable name was reported by `assert()` (#182). * Checks on POSIXct dates with storage mode integer should now work instead of raising an exception (#175). * `*Matrix()` and `*Array()` now allow different storage types than the one specified if all values are missing (#184). * Function `assert()` now supports collecting assertions via `AssertCollection` (#112). * New exported C function `qcheck()` (#180). * Fixed a bug in `checkFunction(..., ordered = TRUE)` (#204). * Removed deprecated S macro `DOUBLE_EPS` from C source. # Version 2.0.0 * Expectations now optionally support the package `tinytest`. `tinytest` is used as backend if it is attached, otherwise checkmate defaults to `testthat`. There is now also a vignette on how to setup `checkmate` for `tinytest`. * Coercion now only affects double vectors. * Improved error message for type detection in `*List`. * Removed `*Bit`, the `bit` package is orphaned. * Fixed documentation. # Version 1.9.4 * Fixed factors being detected as integerish. * Fixed error message for name checks of vectors. # Version 1.9.3 * New argument `extension` for `checkPathForOutput()` (#162). * Fixed handling of different NA types in all set functions (#158). * `expect_vector` removed due to a nameclash with package `testthat`. # Version 1.9.2 * `assert*(..., coerce = TRUE)` does not drop names during conversion (#157), thanks to @mb706. * Fixed documentation in `checkDataFrame` (#159), thanks to @harvey131. * Changed heuristic in `vname()` to improve lookup of variable names. # Version 1.9.1 * Fix segfault on Solaris * Fix warnings reported by rchk * Fix checking private slots in `checkR6` (#156) # Version 1.9.0 * Error messages now provide more information about error locations, e.g., the position of the first missing element in a vector. * If the object to check is missing, `assert`-functions now give a better error message, `test`-functions are always `FALSE` and `expect`-functions always raise an exception. * Checks for missingness and sort order optimized for ALTREPs. * The calling frame reported in assertions is now identical to the calling frame reported by R's `stop()` function (#117). * Added `checkDouble` to explicitly check for non-integer numerics. * Added `checkRaw` to check raw vectors. * Added `checkFormula` to check formula objects. * Added `checkMultiClass` to check for inheritance from a set of candidates * Added `checkDisjunct` to check sets for being disjunct. * Added abbreviation `"p"` to qassert to check for POSIXct objects. * Added argument `coerce` to `assertCount`/`assert_count`, `assertInt`/`assert_int` and `assertIntegerish`/`assert_integerish` which optionally coerces `x` to integer after an successful assertion. This supersedes the functions `asCount`, `asInt` and `asInteger` (#77). * Added arguments `max.rows` and `max.cols` to check for maximum number of rows and columns for matrices, data.frames, tibbles and data.tables. * Added argument `disjunct.from` to `*Names`. * Fixed an error message in `checkChoice`. * Fixed `*Function` to work properly with Primitives. * Fixed `*List` where the check for missingness was broken. * Workaround for `*DataTable` for the detection of the number of rows of null data.tables: # 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/inst/0000755000176200001440000000000014651660101013153 5ustar liggesuserscheckmate/inst/include/0000755000176200001440000000000014245411067014602 5ustar liggesuserscheckmate/inst/include/checkmate_stub.c0000644000176200001440000000140714245411067017731 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); } SEXP qcheck(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", "qcheck"); return fun(x, rule, name); } checkmate/inst/include/checkmate.h0000644000176200001440000000070214245411067016676 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); SEXP attribute_hidden qcheck(SEXP x, const char *rule, const char *name); #ifdef __cplusplus } #endif #endif checkmate/inst/CITATION0000644000176200001440000000046714245411067014323 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, doi = "10.32614/RJ-2017-028", pages = "437--445", volume = 9L, number = 1L ) # vim: ft=r checkmate/inst/doc/0000755000176200001440000000000014651660101013720 5ustar liggesuserscheckmate/inst/doc/checkmate.R0000644000176200001440000001277314651660101016001 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]") # }) ## ----fig.width=6,fig.height=4,dependson="init",eval=requireNamespace("microbenchmark", quietly = TRUE)---- library(checkmate) 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) ## ----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) ## ----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) ## ----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) ## ----fig.width=6,fig.height=4,eval=requireNamespace("microbenchmark", quietly = TRUE)---- N = 10000 x.altrep = seq_len(N) # this is an ALTREP in R version >= 3.5.0 x.sexp = c(x.altrep) # this is a regular SEXP OTOH r = function(x) stopifnot(is.integer(x), !any(is.na(x)), !is.unsorted(x)) cm = function(x) assertInteger(x, any.missing = FALSE, sorted = TRUE) mb = microbenchmark(r(x.sexp), cm(x.sexp), r(x.altrep), cm(x.altrep)) 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) ## ----eval = FALSE, hilang = "c"----------------------------------------------- # SEXP qassert(SEXP x, const char *rule, const char *name); # Rboolean qtest(SEXP x, const char *rule); ## ----eval = FALSE, hilang = "c"----------------------------------------------- # #include # #include ## ----------------------------------------------------------------------------- sessionInfo() checkmate/inst/doc/tinytest.R0000644000176200001440000000022714651660101015727 0ustar liggesusers## ----eval=FALSE--------------------------------------------------------------- # library("tinytest") # library("checkmate") # using("checkmate") checkmate/inst/doc/tinytest.Rmd0000644000176200001440000000221114245411067016247 0ustar liggesusers--- title: "Setup tinytest" author: "Michel Lang" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Setup tinytest} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ## Setup `tinytest` Setting up the `tinytest` framework is covered in detail in the documentation of [tinytest](https://cran.r-project.org/package=tinytest). Quick summary: 1. In the package root directory, call `tinytest::setup_tinytest(".")`. 2. Edit/add R scripts with unit tests to the directory `inst/tinytest`. ## Setup `checkmate` 1. Edit your `DESCRIPTION` and add `checkmate` to `Suggests` unless it is already listed in `Imports` for its assertions. 2. In **each** test file which calls an expectation from `checkmate`, you must include the following lines at the beginning of the file: ```{r,eval=FALSE} library("tinytest") library("checkmate") using("checkmate") ``` If you forget the last line, expectations will not get reported correctly in the summary. Also note that sourcing a file which includes `using("checkmate")` is **not** sufficient. 3. Check if everything works with `R CMD check`. checkmate/inst/doc/checkmate.html0000644000176200001440000057011414651660101016542 0ustar liggesusers Checkmate

Checkmate

Michel Lang

2024-07-29

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 these 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(checkmate)
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))
## Warning in microbenchmark(r(x), cm(x), cmq(x)): less accurate nanosecond times
## to avoid potential integer overflows
print(mb)
## Unit: nanoseconds
##    expr  min   lq     mean median   uq     max neval cld
##    r(x) 2296 2337 16416.40   2378 2460 1390105   100   a
##   cm(x) 1558 1599  6275.46   1640 1722  403645   100   a
##  cmq(x)  984 1025  7812.55   1066 1148  612663   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) 12.710 13.038 32.76064 13.202 13.325 1942.498   100   a
##   cm(x)  4.674  4.797 10.48124  4.879  4.961  494.050   100   a
##  cmq(x)  3.936  4.018  9.92774  4.059  4.141  575.353   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 cld
##    r(x) 178.227 186.9395 205.36818 189.3380 192.987 1616.261   100  a 
##   cm(x)  70.725  71.1350  79.09310  71.3195  71.545  671.416   100   b
##  cmq(x)  77.695  77.9000  85.11477  81.4875  81.672  520.249   100   b
autoplot(mb)

Benchmark 4: Test 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) 75.276 83.681 101.34626 84.624 86.1205 1635.449   100  a 
##   cm(x) 29.684 29.971  36.43137 30.094 30.2170  471.090   100   b
##  cmq(x) 24.846 24.969  31.29325 25.010 25.1330  585.726   100   b
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) 62689 68347 72084.15 71668.0 73144 113939   100 a  
##   cm(x)  3772  3977  4513.28  4202.5  4387  21976   100  b 
##  cmq(x)   615   656   861.41   779.0   902   8487   100   c
autoplot(mb)

Benchmark 5: Assert that x is an increasing sequence of integers with no missing values

N = 10000
x.altrep = seq_len(N) # this is an ALTREP in R version >= 3.5.0
x.sexp = c(x.altrep)  # this is a regular SEXP OTOH
r = function(x) stopifnot(is.integer(x), !any(is.na(x)), !is.unsorted(x))
cm = function(x) assertInteger(x, any.missing = FALSE, sorted = TRUE)
mb = microbenchmark(r(x.sexp), cm(x.sexp), r(x.altrep), cm(x.altrep))
print(mb)
## Unit: microseconds
##          expr    min      lq     mean  median      uq      max neval cld
##     r(x.sexp) 33.497 36.7975 38.15337 37.2075 37.8430   56.334   100 ab 
##    cm(x.sexp) 14.596 14.7600 15.53326 14.8830 15.1290   73.308   100 a c
##   r(x.altrep) 36.982 40.3030 55.73212 40.6720 41.6970 1481.781   100  b 
##  cm(x.altrep)  2.501  2.6240  7.40378  2.8290  3.0135  456.822   100   c
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 = checkmate::vname(x), add = NULL) 
## {
##     if (missing(x)) 
##         stop(sprintf("argument \"%s\" is missing, with no default", 
##             .var.name))
##     res = checkSquareMatrix(x, mode)
##     checkmate::makeAssertion(x, res, .var.name, add)
## }
# For tests:
test_square_matrix = testSquareMatrix = makeTestFunction(checkSquareMatrix)
print(testSquareMatrix)
## function (x, mode = NULL) 
## {
##     isTRUE(checkSquareMatrix(x, mode))
## }
# For expectations:
expect_square_matrix = makeExpectationFunction(checkSquareMatrix)
print(expect_square_matrix)
## function (x, mode = NULL, info = NULL, label = vname(x)) 
## {
##     if (missing(x)) 
##         stop(sprintf("Argument '%s' is missing", label))
##     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 below.
  3. Include the provided header file <checkmate.h> in each compilation unit where you want to use checkmate.

File contents for (2):

#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 4.4.1 (2024-06-14)
## Platform: aarch64-apple-darwin20
## Running under: macOS Sonoma 14.5
## 
## Matrix products: default
## BLAS:   /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRblas.0.dylib 
## LAPACK: /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.0
## 
## locale:
## [1] C/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
## 
## time zone: Europe/Berlin
## tzcode source: internal
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] microbenchmark_1.4.10 ggplot2_3.5.1         checkmate_2.3.2      
## 
## loaded via a namespace (and not attached):
##  [1] Matrix_1.5-4         gtable_0.3.5         jsonlite_1.8.8      
##  [4] highr_0.11           dplyr_1.1.4          compiler_4.4.1      
##  [7] tidyselect_1.2.1     jquerylib_0.1.4      splines_4.4.1       
## [10] scales_1.3.0         yaml_2.3.10          fastmap_1.2.0       
## [13] TH.data_1.1-2        lattice_0.22-6       R6_2.5.1            
## [16] generics_0.1.3       knitr_1.48           MASS_7.3-59         
## [19] backports_1.4.1-9001 tibble_3.2.1         munsell_0.5.1       
## [22] bslib_0.7.0          pillar_1.9.0         rlang_1.1.4         
## [25] utf8_1.2.4           multcomp_1.4-26      cachem_1.1.0        
## [28] xfun_0.46            sass_0.4.9           cli_3.6.3           
## [31] withr_3.0.0          magrittr_2.0.3       digest_0.6.36       
## [34] grid_4.4.1           mvtnorm_1.2-5        sandwich_3.1-0      
## [37] lifecycle_1.0.4      vctrs_0.6.5          evaluate_0.24.0     
## [40] glue_1.7.0           farver_2.1.2         codetools_0.2-20    
## [43] zoo_1.8-12           survival_3.6-4       fansi_1.0.6         
## [46] colorspace_2.1-1     rmarkdown_2.27       tools_4.4.1         
## [49] pkgconfig_2.0.3      htmltools_0.5.8.1
checkmate/inst/doc/checkmate.Rmd0000644000176200001440000003107214245411067016317 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 these 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,fig.width=6,fig.height=4,dependson="init",eval=requireNamespace("microbenchmark", quietly = TRUE)} library(checkmate) 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,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,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: Test that `x` is a data frame with no missing values ```{r,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) ``` ### Benchmark 5: Assert that `x` is an increasing sequence of integers with no missing values ```{r,fig.width=6,fig.height=4,eval=requireNamespace("microbenchmark", quietly = TRUE)} N = 10000 x.altrep = seq_len(N) # this is an ALTREP in R version >= 3.5.0 x.sexp = c(x.altrep) # this is a regular SEXP OTOH r = function(x) stopifnot(is.integer(x), !any(is.na(x)), !is.unsorted(x)) cm = function(x) assertInteger(x, any.missing = FALSE, sorted = TRUE) mb = microbenchmark(r(x.sexp), cm(x.sexp), r(x.altrep), cm(x.altrep)) 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. ```{r, eval = FALSE, hilang = "c"} 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](https://r-pkgs.org/src.html#c-export) 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 below. 3. Include the provided header file `` in each compilation unit where you want to use checkmate. File contents for (2): ```{r, eval = FALSE, hilang = "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/tinytest.html0000644000176200001440000002407714651660101016503 0ustar liggesusers Setup tinytest

Setup tinytest

Michel Lang

2024-07-29

Setup tinytest

Setting up the tinytest framework is covered in detail in the documentation of tinytest. Quick summary:

  1. In the package root directory, call tinytest::setup_tinytest(".").
  2. Edit/add R scripts with unit tests to the directory inst/tinytest.

Setup checkmate

  1. Edit your DESCRIPTION and add checkmate to Suggests unless it is already listed in Imports for its assertions.

  2. In each test file which calls an expectation from checkmate, you must include the following lines at the beginning of the file:

    library("tinytest")
    library("checkmate")
    using("checkmate")

    If you forget the last line, expectations will not get reported correctly in the summary. Also note that sourcing a file which includes using("checkmate") is not sufficient.

  3. Check if everything works with R CMD check.

checkmate/README.md0000644000176200001440000000377114245411067013471 0ustar liggesusers# checkmate [![CRAN_Status_Badge](https://www.r-pkg.org/badges/version/checkmate)](https://cran.r-project.org/package=checkmate) [![R build status](https://github.com/mllg/checkmate/workflows/R-CMD-check/badge.svg)](https://github.com/mllg/checkmate) [![Coverage Status](https://img.shields.io/coveralls/mllg/checkmate.svg)](https://coveralls.io/github/mllg/checkmate) [![Download Stats](https://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/build/0000755000176200001440000000000014651660101013275 5ustar liggesuserscheckmate/build/vignette.rds0000644000176200001440000000033614651660101015636 0ustar liggesusersuM0 b< luᶁv/qi׾קR R58j.iȄc3©w"<N`N;,-?Y*N@hB=SD'='eI*?> ,;4 mdVEav v(L $"‰A+checkmate/man/0000755000176200001440000000000014646733165012770 5ustar liggesuserscheckmate/man/checkVector.Rd0000644000176200001440000001075714646134410015515 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} \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 ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{strict}{[\code{logical(1)}]\cr May the vector have additional attributes? If \code{TRUE}, mimics the behavior of \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 no non-missing values allowed? Default is \code{TRUE}. Note that empty vectors do not have non-missing values.} \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}}.} } \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}/\code{check_vector} return 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{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()} Other atomicvector: \code{\link{checkAtomic}()}, \code{\link{checkAtomicVector}()} } \concept{atomicvector} \concept{basetypes} checkmate/man/checkString.Rd0000644000176200001440000001064614646134410015516 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, n.chars = NULL, min.chars = NULL, max.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE ) check_string( x, na.ok = FALSE, n.chars = NULL, min.chars = NULL, max.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE ) assertString( x, na.ok = FALSE, n.chars = NULL, min.chars = NULL, max.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_string( x, na.ok = FALSE, n.chars = NULL, min.chars = NULL, max.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL ) testString( x, na.ok = FALSE, n.chars = NULL, min.chars = NULL, max.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE ) test_string( x, na.ok = FALSE, n.chars = NULL, min.chars = NULL, max.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE ) expect_string( x, na.ok = FALSE, n.chars = NULL, min.chars = NULL, max.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{n.chars}{[\code{integer(1)}]\cr Exact number of characters for each element of \code{x}.} \item{min.chars}{[\code{integer(1)}]\cr Minimum number of characters for each element of \code{x}.} \item{max.chars}{[\code{integer(1)}]\cr Maximum 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}{[\code{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}/\code{check_string} return 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. To check for vectors of arbitrary length, see \code{\link{checkCharacter}}. } \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{checkScalar}()}, \code{\link{checkScalarNA}()} } \concept{scalars} checkmate/man/checkAtomic.Rd0000644000176200001440000001107414646134410015460 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 no non-missing values allowed? Default is \code{TRUE}. Note that empty vectors do not have non-missing values.} \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}{[\code{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}/\code{check_atomic} return 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}}. Note that `NULL` is recognized as a valid atomic value, as in R versions up to version 4.3.x. For details, see \url{https://stat.ethz.ch/pipermail/r-devel/2023-September/082892.html}. } \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{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} Other atomicvector: \code{\link{checkAtomicVector}()}, \code{\link{checkVector}()} } \concept{atomicvector} \concept{basetypes} checkmate/man/anyInfinite.Rd0000644000176200001440000000105314245411067015520 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/checkNull.Rd0000644000176200001440000000405714646134410015161 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}/\code{check_null} return 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{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkDouble.Rd0000644000176200001440000001414214646134410015455 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkDouble.R \name{checkDouble} \alias{checkDouble} \alias{check_double} \alias{assertDouble} \alias{assert_double} \alias{testDouble} \alias{test_double} \alias{expect_double} \title{Check that an argument is a vector of type double} \usage{ checkDouble( 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, typed.missing = FALSE, null.ok = FALSE ) check_double( 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, typed.missing = FALSE, null.ok = FALSE ) assertDouble( 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, typed.missing = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_double( 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, typed.missing = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL ) testDouble( 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, typed.missing = FALSE, null.ok = FALSE ) test_double( 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, typed.missing = FALSE, null.ok = FALSE ) expect_double( 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, typed.missing = FALSE, 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 or equal to.} \item{upper}{[\code{numeric(1)}]\cr Upper value all elements of \code{x} must be lower than or equal to.} \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 no non-missing values allowed? Default is \code{TRUE}. Note that empty vectors do not have non-missing values.} \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{typed.missing}{[\code{logical(1)}]\cr If set to \code{FALSE} (default), all types of missing values (\code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_character_} or \code{NA_character_}) as well as empty vectors are allowed while type-checking atomic input. Set to \code{TRUE} to enable strict type checking.} \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}{[\code{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{assertDouble}/\code{assert_double} return \code{x} invisibly, whereas \code{checkDouble}/\code{check_double} and \code{testDouble}/\code{test_double} return \code{TRUE}. If the check is not successful, \code{assertDouble}/\code{assert_double} throws an error message, \code{testDouble}/\code{test_double} returns \code{FALSE}, and \code{checkDouble}/\code{check_double} return a string with the error message. The function \code{expect_double} always returns an \code{\link[testthat]{expectation}}. } \description{ Check that an argument is a vector of type double } \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{ testDouble(1) testDouble(1L) testDouble(1, min.len = 1, lower = 0) } \seealso{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkArray.Rd0000644000176200001440000001060014646134410015314 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). If all values of \code{x} are missing, this check is skipped.} \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}{[\code{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}/\code{check_array} return 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{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} Other compound: \code{\link{checkDataFrame}()}, \code{\link{checkDataTable}()}, \code{\link{checkMatrix}()}, \code{\link{checkTibble}()} } \concept{basetypes} \concept{compound} checkmate/man/checkTRUE.Rd0000644000176200001440000000313614245411067015024 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.}/\code{check_true.} return 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/checkRaw.Rd0000644000176200001440000000723714646134410015003 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkRaw.R \name{checkRaw} \alias{checkRaw} \alias{check_raw} \alias{assertRaw} \alias{assert_raw} \alias{testRaw} \alias{test_raw} \alias{expect_raw} \title{Check if an argument is a raw vector} \usage{ checkRaw( x, len = NULL, min.len = NULL, max.len = NULL, names = NULL, null.ok = FALSE ) check_raw( x, len = NULL, min.len = NULL, max.len = NULL, names = NULL, null.ok = FALSE ) assertRaw( x, len = NULL, min.len = NULL, max.len = NULL, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_raw( x, len = NULL, min.len = NULL, max.len = NULL, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) testRaw( x, len = NULL, min.len = NULL, max.len = NULL, names = NULL, null.ok = FALSE ) test_raw( x, len = NULL, min.len = NULL, max.len = NULL, names = NULL, null.ok = FALSE ) expect_raw( x, len = NULL, min.len = NULL, max.len = NULL, names = 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{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}{[\code{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{assertRaw}/\code{assert_raw} return \code{x} invisibly, whereas \code{checkRaw}/\code{check_raw} and \code{testRaw}/\code{test_raw} return \code{TRUE}. If the check is not successful, \code{assertRaw}/\code{assert_raw} throws an error message, \code{testRaw}/\code{test_raw} returns \code{FALSE}, and \code{checkRaw}/\code{check_raw} return a string with the error message. The function \code{expect_raw} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a raw vector } \examples{ testRaw(as.raw(2), min.len = 1L) } \seealso{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/makeAssertion.Rd0000644000176200001440000000604114245411067016052 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, use.namespace = TRUE, coerce = FALSE, 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{use.namespace}{[\code{logical(1)}]\cr Call functions of \pkg{checkmate} using its namespace explicitly. Can be set to \code{FALSE} so save some microseconds, but the checkmate package needs to be imported. Default is \code{TRUE}.} \item{coerce}{[\code{logical(1)}]\cr If \code{TRUE}, injects some lines of code to convert numeric values to integer after an successful assertion. Currently used in \code{\link{assertCount}}, \code{\link{assertInt}} and \code{\link{assertIntegerish}}.} \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}()} } \concept{CustomConstructors} checkmate/man/wf.Rd0000644000176200001440000000140414245411067013657 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/checkComplex.Rd0000644000176200001440000001234014646134410015650 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, typed.missing = FALSE, null.ok = FALSE ) check_complex( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE ) assertComplex( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, typed.missing = FALSE, 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, typed.missing = FALSE, 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, typed.missing = FALSE, null.ok = FALSE ) test_complex( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE ) expect_complex( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, typed.missing = FALSE, 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 no non-missing values allowed? Default is \code{TRUE}. Note that empty vectors do not have non-missing values.} \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{typed.missing}{[\code{logical(1)}]\cr If set to \code{FALSE} (default), all types of missing values (\code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_character_} or \code{NA_character_}) as well as empty vectors are allowed while type-checking atomic input. Set to \code{TRUE} to enable strict type checking.} \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}{[\code{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}/\code{check_complex} return 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{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkMultiClass.Rd0000644000176200001440000000544114245411067016326 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkMultiClass.R \name{checkMultiClass} \alias{checkMultiClass} \alias{check_multi_class} \alias{assertMultiClass} \alias{assert_multi_class} \alias{testMultiClass} \alias{test_multi_class} \alias{expect_multi_class} \title{Check the class membership of an argument} \usage{ checkMultiClass(x, classes, null.ok = FALSE) check_multi_class(x, classes, null.ok = FALSE) assertMultiClass(x, classes, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_multi_class( x, classes, null.ok = FALSE, .var.name = vname(x), add = NULL ) testMultiClass(x, classes, null.ok = FALSE) test_multi_class(x, classes, null.ok = FALSE) expect_multi_class(x, classes, 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}}. \code{x} must inherit from any of the specified classes.} \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}{[\code{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{assertMultiClass}/\code{assert_multi_class} return \code{x} invisibly, whereas \code{checkMultiClass}/\code{check_multi_class} and \code{testMultiClass}/\code{test_multi_class} return \code{TRUE}. If the check is not successful, \code{assertMultiClass}/\code{assert_multi_class} throws an error message, \code{testMultiClass}/\code{test_multi_class} returns \code{FALSE}, and \code{checkMultiClass}/\code{check_multi_class} return a string with the error message. The function \code{expect_multi_class} always returns an \code{\link[testthat]{expectation}}. } \description{ Check the class membership of an argument } \examples{ x = 1 class(x) = "bar" checkMultiClass(x, c("foo", "bar")) checkMultiClass(x, c("foo", "foobar")) } \seealso{ Other attributes: \code{\link{checkClass}()}, \code{\link{checkNamed}()}, \code{\link{checkNames}()} Other classes: \code{\link{checkClass}()}, \code{\link{checkR6}()} } \concept{attributes} \concept{classes} checkmate/man/checkList.Rd0000644000176200001440000001377714646134410015173 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 no non-missing values allowed? Default is \code{TRUE}. Note that empty vectors do not have non-missing values.} \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}{[\code{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{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}/\code{check_list} return 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{ Contrary to R's \code{\link[base]{is.list}}, objects of type \code{\link[base]{data.frame}} and \code{\link[base]{pairlist}} are not recognized as list. Missingness is defined here as elements of the list being \code{NULL}, analogously to \code{\link{anyMissing}}. The test for uniqueness does differentiate between the different NA types which are built-in in R. This is required 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")) # Missingness testList(list(1, NA), any.missing = FALSE) testList(list(1, NULL), any.missing = FALSE) # 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{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkDate.Rd0000644000176200001440000001122214646134410015114 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 no non-missing values allowed? Default is \code{TRUE}. Note that empty vectors do not have non-missing values.} \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}{[\code{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}/\code{check_atomic} return 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{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkFactor.Rd0000644000176200001440000001416014646134410015461 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 no non-missing values allowed? Default is \code{TRUE}. Note that empty vectors do not have non-missing values.} \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}{[\code{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}/\code{check_factor} return 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{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkOS.Rd0000644000176200001440000000346514245411067014573 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}{[\code{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}/\code{check_os} return 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/checkNamed.Rd0000644000176200001440000000440514245411067015271 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}/\code{check_named} return 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{checkMultiClass}()}, \code{\link{checkNames}()} } \concept{attributes} checkmate/man/checkMatrix.Rd0000644000176200001440000001366714646134410015522 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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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). If all values of \code{x} are missing, this check is skipped.} \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{max.rows}{[\code{integer(1)}]\cr Maximum number of rows.} \item{min.cols}{[\code{integer(1)}]\cr Minimum number of columns.} \item{max.cols}{[\code{integer(1)}]\cr Maximum 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}{[\code{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}/\code{check_matrix} return 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{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} Other compound: \code{\link{checkArray}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDataTable}()}, \code{\link{checkTibble}()} } \concept{basetypes} \concept{compound} checkmate/man/coalesce.Rd0000644000176200001440000000117614245411067015027 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/checkScalar.Rd0000644000176200001440000000534414245411067015455 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}{[\code{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}/\code{check_scalar} return 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}()} } \concept{scalars} checkmate/man/makeTest.Rd0000644000176200001440000000374714245411067015034 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}()} } \concept{CustomConstructors} checkmate/man/anyNaN.Rd0000644000176200001440000000076414245411067014437 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/checkDataFrame.Rd0000644000176200001440000001446414646134410016076 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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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 columns with only missing values allowed? Default is \code{TRUE}.} \item{min.rows}{[\code{integer(1)}]\cr Minimum number of rows.} \item{max.rows}{[\code{integer(1)}]\cr Maximum number of rows.} \item{min.cols}{[\code{integer(1)}]\cr Minimum number of columns.} \item{max.cols}{[\code{integer(1)}]\cr Maximum 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}{[\code{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}/\code{check_data_frame} return 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{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} \concept{compound} checkmate/man/checkR6.Rd0000644000176200001440000000713714245411067014541 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 an 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}}. \code{x} must inherit from all specified classes.} \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}{[\code{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}/\code{check_class} return a string with the error message. The function \code{expect_class} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is an 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") } \seealso{ Other classes: \code{\link{checkClass}()}, \code{\link{checkMultiClass}()} } \concept{classes} checkmate/man/checkAccess.Rd0000644000176200001440000000462214245411067015447 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}{[\code{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}/\code{check_access} return 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}()} } \concept{filesystem} checkmate/man/asInteger.Rd0000644000176200001440000000622014245411067015165 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 or equal to.} \item{upper}{[\code{numeric(1)}]\cr Upper value all elements of \code{x} must be lower than or equal to.} \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 no non-missing values allowed? Default is \code{TRUE}. Note that empty vectors do not have non-missing values.} \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. Note that these functions may be deprecated in the future. Instead, it is advised to use \code{\link{assertCount}}, \code{\link{assertInt}} or \code{\link{assertIntegerish}} with argument \code{coerce} set to \code{TRUE} instead. } \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/checkPOSIXct.Rd0000644000176200001440000001172214646134410015475 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 no non-missing values allowed? Default is \code{TRUE}. Note that empty vectors do not have non-missing values.} \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}{[\code{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}/\code{check_atomic} return 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{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkNames.Rd0000644000176200001440000001207514646733243015322 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, disjunct.from = NULL, what = "names" ) check_names( x, type = "named", subset.of = NULL, must.include = NULL, permutation.of = NULL, identical.to = NULL, disjunct.from = NULL, what = "names" ) assertNames( x, type = "named", subset.of = NULL, must.include = NULL, permutation.of = NULL, identical.to = NULL, disjunct.from = NULL, what = "names", .var.name = vname(x), add = NULL ) assert_names( x, type = "named", subset.of = NULL, must.include = NULL, permutation.of = NULL, identical.to = NULL, disjunct.from = NULL, what = "names", .var.name = vname(x), add = NULL ) testNames( x, type = "named", subset.of = NULL, must.include = NULL, permutation.of = NULL, identical.to = NULL, disjunct.from = NULL, what = "names" ) test_names( x, type = "named", subset.of = NULL, must.include = NULL, permutation.of = NULL, identical.to = NULL, disjunct.from = NULL, what = "names" ) expect_names( x, type = "named", subset.of = NULL, must.include = NULL, permutation.of = NULL, identical.to = NULL, disjunct.from = NULL, what = "names", 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._]*$}.} \item{ids:}{Same as \dQuote{strict}, but does not enforce uniqueness.} } 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{disjunct.from}{[\code{character}]\cr Names provided in \code{x} must may not be present in the vector \code{disjunct.from}.} \item{what}{[\code{character(1)}]\cr Type of name vector to check, e.g. \dQuote{names} (default), \dQuote{colnames} or \dQuote{rownames}.} \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}{[\code{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{assertNames}/\code{assert_names} return \code{x} invisibly, whereas \code{checkNames}/\code{check_names} and \code{testNames}/\code{test_names} return \code{TRUE}. If the check is not successful, \code{assertNames}/\code{assert_names} throws an error message, \code{testNames}/\code{test_names} returns \code{FALSE}, and \code{checkNames}/\code{check_names} return a string with the error message. The function \code{expect_names} always returns an \code{\link[testthat]{expectation}}. } \description{ Performs various checks on character vectors, usually names. } \examples{ x = 1:3 testNames(names(x), "unnamed") names(x) = letters[1:3] testNames(names(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{checkMultiClass}()}, \code{\link{checkNamed}()} } \concept{attributes} checkmate/man/checkInt.Rd0000644000176200001440000000747714646134410015012 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, coerce = 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, coerce = 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 or equal to.} \item{upper}{[\code{numeric(1)}]\cr Upper value all elements of \code{x} must be lower than or equal to.} \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{coerce}{[\code{logical(1)}]\cr If \code{TRUE}, the input \code{x} is returned as integer after an successful assertion.} \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}{[\code{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}/\code{check_int} return 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{checkScalar}()}, \code{\link{checkScalarNA}()}, \code{\link{checkString}()} } \concept{scalars} checkmate/man/checkSubset.Rd0000644000176200001440000000641114423162567015517 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}{[\code{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}/\code{check_subset} return 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{checkDisjunct}()}, \code{\link{checkPermutation}()}, \code{\link{checkSetEqual}()} } \concept{set} checkmate/man/checkPermutation.Rd0000644000176200001440000000566614423162567016574 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkPermutation.R \name{checkPermutation} \alias{checkPermutation} \alias{check_permutation} \alias{assertPermutation} \alias{assert_permutation} \alias{testPermutation} \alias{test_permutation} \alias{expect_permutation} \title{Check if the arguments are permutations of each other.} \usage{ checkPermutation(x, y, na.ok = TRUE) check_permutation(x, y, na.ok = TRUE) assertPermutation(x, y, na.ok = TRUE, .var.name = vname(x), add = NULL) assert_permutation(x, y, na.ok = TRUE, .var.name = vname(x), add = NULL) testPermutation(x, y, na.ok = TRUE) test_permutation(x, y, na.ok = TRUE) expect_permutation(x, y, na.ok = TRUE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{y}{[\code{atomic}]\cr Vector to compare with. Atomic vector of type other than raw.} \item{na.ok}{[\code{logical(1)}]\cr Are missing values allowed? Default is \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}}.} \item{info}{[\code{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{assertPermutation}/\code{assert_permutation} return \code{x} invisibly, whereas \code{checkPermutation}/\code{check_permutation} and \code{testPermutation}/\code{test_permutation} return \code{TRUE}. If the check is not successful, \code{assertPermutation}/\code{assert_permutation} throws an error message, \code{testPermutation}/\code{test_permutation} returns \code{FALSE}, and \code{checkPermutation}/\code{check_permutation} return a string with the error message. The function \code{expect_permutation} always returns an \code{\link[testthat]{expectation}}. } \description{ In contrast to \code{\link{checkSetEqual}}, the function tests for a true permutation of the two vectors and also considers duplicated values. Missing values are being treated as actual values by default. Does not work on raw values. } \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{ testPermutation(letters[1:2], letters[2:1]) testPermutation(letters[c(1, 1, 2)], letters[1:2]) testPermutation(c(NA, 1, 2), c(1, 2, NA)) testPermutation(c(NA, 1, 2), c(1, 2, NA), na.ok = FALSE) } \seealso{ Other set: \code{\link{checkChoice}()}, \code{\link{checkDisjunct}()}, \code{\link{checkSetEqual}()}, \code{\link{checkSubset}()} } \concept{set} checkmate/man/register_test_backend.Rd0000644000176200001440000000127314245411067017601 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/makeExpectation.R \name{register_test_backend} \alias{register_test_backend} \title{Select Backend for Unit Tests} \usage{ register_test_backend(name) } \arguments{ \item{name}{[\code{character(1)}]\cr \code{"testthat"} or \code{"tinytest"}.} } \value{ \code{NULL} (invisibly). } \description{ Allows to explicitly select a backend for the unit tests. Currently supported are \code{"testthat"} and \code{"tinytest"}. The respective package must be installed and are loaded (but not attached). If this function is not explicitly called, defaults to \code{"testthat"} unless the \code{"tinytest"}'s namespace is loaded. } checkmate/man/checkInteger.Rd0000644000176200001440000001371614646134410015646 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, typed.missing = FALSE, 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, typed.missing = FALSE, 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, typed.missing = FALSE, 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, typed.missing = FALSE, 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, typed.missing = FALSE, 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, typed.missing = FALSE, 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, typed.missing = FALSE, 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 or equal to.} \item{upper}{[\code{numeric(1)}]\cr Upper value all elements of \code{x} must be lower than or equal to.} \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 no non-missing values allowed? Default is \code{TRUE}. Note that empty vectors do not have non-missing values.} \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{typed.missing}{[\code{logical(1)}]\cr If set to \code{FALSE} (default), all types of missing values (\code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_character_} or \code{NA_character_}) as well as empty vectors are allowed while type-checking atomic input. Set to \code{TRUE} to enable strict type checking.} \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}{[\code{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}/\code{check_integer} return 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{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \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{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkNumeric.Rd0000644000176200001440000001452114646134410015646 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, typed.missing = FALSE, 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, typed.missing = FALSE, 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, typed.missing = FALSE, 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, typed.missing = FALSE, 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, typed.missing = FALSE, 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, typed.missing = FALSE, 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, typed.missing = FALSE, 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 or equal to.} \item{upper}{[\code{numeric(1)}]\cr Upper value all elements of \code{x} must be lower than or equal to.} \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 no non-missing values allowed? Default is \code{TRUE}. Note that empty vectors do not have non-missing values.} \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{typed.missing}{[\code{logical(1)}]\cr If set to \code{FALSE} (default), all types of missing values (\code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_character_} or \code{NA_character_}) as well as empty vectors are allowed while type-checking atomic input. Set to \code{TRUE} to enable strict type checking.} \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}{[\code{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}/\code{check_numeric} return a string with the error message. The function \code{expect_numeric} always returns an \code{\link[testthat]{expectation}}. } \description{ Vectors of storage type \dQuote{integer} and \dQuote{double} count as \dQuote{numeric}, c.f. \code{\link[base]{is.numeric}}. To explicitly check for real integer or double vectors, see \code{\link{checkInteger}}, \code{\link{checkIntegerish}} or \code{\link{checkDouble}}. } \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{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/matchArg.Rd0000644000176200001440000000212614245411067014773 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/qassertr.Rd0000644000176200001440000000365214245411067015116 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}{[\code{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/checkDisjunct.Rd0000644000176200001440000000564114423162567016041 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkDisjunct.R \name{checkDisjunct} \alias{checkDisjunct} \alias{check_disjunct} \alias{assertDisjunct} \alias{assert_disjunct} \alias{testDisjunct} \alias{test_disjunct} \alias{expect_disjunct} \title{Check if an argument is disjunct from a given set} \usage{ checkDisjunct(x, y, fmatch = FALSE) check_disjunct(x, y, fmatch = FALSE) assertDisjunct(x, y, fmatch = FALSE, .var.name = vname(x), add = NULL) assert_disjunct(x, y, fmatch = FALSE, .var.name = vname(x), add = NULL) testDisjunct(x, y, fmatch = FALSE) test_disjunct(x, y, fmatch = FALSE) expect_disjunct(x, y, fmatch = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{y}{[\code{atomic}]\cr Other Set.} \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}{[\code{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{assertDisjunct}/\code{assert_disjunct} return \code{x} invisibly, whereas \code{checkDisjunct}/\code{check_disjunct} and \code{testDisjunct}/\code{test_disjunct} return \code{TRUE}. If the check is not successful, \code{assertDisjunct}/\code{assert_disjunct} throws an error message, \code{testDisjunct}/\code{test_disjunct} returns \code{FALSE}, and \code{checkDisjunct}/\code{check_disjunct} return a string with the error message. The function \code{expect_disjunct} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is disjunct from 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{ testDisjunct(1L, letters) testDisjunct(c("a", "z"), letters) # x is not converted before the comparison (except for numerics) testDisjunct(factor("a"), "a") testDisjunct(1, "1") testDisjunct(1, as.integer(1)) } \seealso{ Other set: \code{\link{checkChoice}()}, \code{\link{checkPermutation}()}, \code{\link{checkSetEqual}()}, \code{\link{checkSubset}()} } \concept{set} checkmate/man/checkDirectoryExists.Rd0000644000176200001440000000644614245411067017420 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}{[\code{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}/\code{check_directory_exists} return 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}()} } \concept{filesystem} checkmate/man/checkIntegerish.Rd0000644000176200001440000001544114646134410016347 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, typed.missing = FALSE, 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, typed.missing = FALSE, 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, typed.missing = FALSE, null.ok = FALSE, coerce = 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, typed.missing = FALSE, null.ok = FALSE, coerce = 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, typed.missing = FALSE, 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, typed.missing = FALSE, 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, typed.missing = FALSE, 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 or equal to.} \item{upper}{[\code{numeric(1)}]\cr Upper value all elements of \code{x} must be lower than or equal to.} \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 no non-missing values allowed? Default is \code{TRUE}. Note that empty vectors do not have non-missing values.} \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{typed.missing}{[\code{logical(1)}]\cr If set to \code{FALSE} (default), all types of missing values (\code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_character_} or \code{NA_character_}) as well as empty vectors are allowed while type-checking atomic input. Set to \code{TRUE} to enable strict type checking.} \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{coerce}{[\code{logical(1)}]\cr If \code{TRUE}, the input \code{x} is returned as integer after an successful assertion.} \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}{[\code{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}/\code{check_integerish} return 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 sufficiently close to an integer w.r.t. a numeric tolerance `tol`. } \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{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \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{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkTibble.Rd0000644000176200001440000001305114245411067015443 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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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{max.rows}{[\code{integer(1)}]\cr Maximum number of rows.} \item{min.cols}{[\code{integer(1)}]\cr Minimum number of columns.} \item{max.cols}{[\code{integer(1)}]\cr Maximum 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}{[\code{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}/\code{check_tibble} return 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}()} } \concept{compound} checkmate/man/checkEnvironment.Rd0000644000176200001440000000650614646134410016554 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}{[\code{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}/\code{check_environment} return 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{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkChoice.Rd0000644000176200001440000000632714423162567015452 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}{[\code{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}/\code{check_choice} return 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{checkDisjunct}()}, \code{\link{checkPermutation}()}, \code{\link{checkSetEqual}()}, \code{\link{checkSubset}()} } \concept{set} checkmate/man/checkDataTable.Rd0000644000176200001440000001417114245411067016067 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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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, max.rows = NULL, min.cols = NULL, max.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{max.rows}{[\code{integer(1)}]\cr Maximum number of rows.} \item{min.cols}{[\code{integer(1)}]\cr Minimum number of columns.} \item{max.cols}{[\code{integer(1)}]\cr Maximum 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}{[\code{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}/\code{check_data_table} return 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}()} } \concept{compound} checkmate/man/checkAtomicVector.Rd0000644000176200001440000001153414646134410016644 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}{[\code{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}/\code{check_atomic_vector} return 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 basically 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{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} Other atomicvector: \code{\link{checkAtomic}()}, \code{\link{checkVector}()} } \concept{atomicvector} \concept{basetypes} checkmate/man/qassert.Rd0000644000176200001440000001112014245411067014721 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}{[\code{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{[pP]} \tab POSIXct date.\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.Rd0000644000176200001440000000610014531605563017027 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, extension = NULL) check_path_for_output(x, overwrite = FALSE, extension = NULL) assertPathForOutput( x, overwrite = FALSE, extension = NULL, .var.name = vname(x), add = NULL ) assert_path_for_output( x, overwrite = FALSE, extension = NULL, .var.name = vname(x), add = NULL ) testPathForOutput(x, overwrite = FALSE, extension = NULL) test_path_for_output(x, overwrite = FALSE, extension = NULL) expect_path_for_output( x, overwrite = FALSE, extension = NULL, 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{extension}{[\code{character(1)}]\cr Extension of the file, e.g. \dQuote{txt} or \dQuote{tar.gz}.} \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}{[\code{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}/\code{check_path_for_output} return 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 used safely 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}()} } \concept{filesystem} checkmate/man/checkFlag.Rd0000644000176200001440000000521214646134410015112 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}{[\code{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}/\code{check_flag} return 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{checkScalar}()}, \code{\link{checkScalarNA}()}, \code{\link{checkString}()} } \concept{scalars} checkmate/man/AssertCollection.Rd0000644000176200001440000000244114245411067016522 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/checkNumber.Rd0000644000176200001440000000663614646134410015504 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 or equal to.} \item{upper}{[\code{numeric(1)}]\cr Upper value all elements of \code{x} must be lower than or equal to.} \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}{[\code{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}/\code{check_number} return 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{checkScalar}()}, \code{\link{checkScalarNA}()}, \code{\link{checkString}()} } \concept{scalars} checkmate/man/assert.Rd0000644000176200001440000000315214646733243014556 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, add = 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 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{ Throws an error (or pushes the error message to an \code{\link{AssertCollection}} if \code{add} is not \code{NULL}) if the 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)) collection <- makeAssertCollection() assert(checkChoice(x, c("a", "b")), checkDataFrame(x), add = collection) collection$getMessages() } checkmate/man/checkFormula.Rd0000644000176200001440000000552514646134410015655 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkFormula.R \name{checkFormula} \alias{checkFormula} \alias{check_formula} \alias{assertFormula} \alias{assert_formula} \alias{testFormula} \alias{test_formula} \alias{expect_formula} \title{Check if an argument is a formula} \usage{ checkFormula(x, null.ok = FALSE) check_formula(x, null.ok = FALSE) assertFormula(x, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_formula(x, null.ok = FALSE, .var.name = vname(x), add = NULL) testFormula(x, null.ok = FALSE) test_formula(x, null.ok = FALSE) expect_formula(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}{[\code{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{assertFormula}/\code{assert_formula} return \code{x} invisibly, whereas \code{checkFormula}/\code{check_formula} and \code{testFormula}/\code{test_formula} return \code{TRUE}. If the check is not successful, \code{assertFormula}/\code{assert_formula} throws an error message, \code{testFormula}/\code{test_formula} returns \code{FALSE}, and \code{checkFormula}/\code{check_formula} return a string with the error message. The function \code{expect_formula} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a formula } \examples{ f = Species ~ Sepal.Length + Sepal.Width checkFormula(f) } \seealso{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkSetEqual.Rd0000644000176200001440000000635714423162567016006 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}{[\code{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}/\code{check_subset} return 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{checkDisjunct}()}, \code{\link{checkPermutation}()}, \code{\link{checkSubset}()} } \concept{set} checkmate/man/checkFileExists.Rd0000644000176200001440000000677114245411067016334 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}{[\code{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}/\code{check_file_exists} return 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}()} } \concept{filesystem} checkmate/man/anyMissing.Rd0000644000176200001440000000275314245411067015374 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{ \code{anyMissing} checks for the presence of at least one missing value, \code{allMissing} checks for the presence of at least one non-missing value. 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 at least 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/makeExpectation.Rd0000644000176200001440000000500614245411067016366 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, use.namespace = FALSE, 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{use.namespace}{[\code{logical(1)}]\cr Call functions of \pkg{checkmate} using its namespace explicitly. Can be set to \code{FALSE} so save some microseconds, but the checkmate package needs to be imported. Default is \code{TRUE}.} \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}()} } \concept{CustomConstructors} checkmate/man/vname.Rd0000644000176200001440000000073114245411067014353 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/checkScalarNA.Rd0000644000176200001440000000472314245411067015674 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}{[\code{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}/\code{check_scalar_na} return 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}()} } \concept{scalars} checkmate/man/checkCharacter.Rd0000644000176200001440000001630714646134410016144 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, n.chars = NULL, min.chars = NULL, max.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, sorted = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE ) check_character( x, n.chars = NULL, min.chars = NULL, max.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, sorted = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE ) assertCharacter( x, n.chars = NULL, min.chars = NULL, max.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, sorted = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_character( x, n.chars = NULL, min.chars = NULL, max.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, sorted = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL ) testCharacter( x, n.chars = NULL, min.chars = NULL, max.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, sorted = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE ) test_character( x, n.chars = NULL, min.chars = NULL, max.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, sorted = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE ) expect_character( x, n.chars = NULL, min.chars = NULL, max.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, sorted = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{n.chars}{[\code{integer(1)}]\cr Exact number of characters for each element of \code{x}.} \item{min.chars}{[\code{integer(1)}]\cr Minimum number of characters for each element of \code{x}.} \item{max.chars}{[\code{integer(1)}]\cr Maximum 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 no non-missing values allowed? Default is \code{TRUE}. Note that empty vectors do not have non-missing values.} \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{typed.missing}{[\code{logical(1)}]\cr If set to \code{FALSE} (default), all types of missing values (\code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_character_} or \code{NA_character_}) as well as empty vectors are allowed while type-checking atomic input. Set to \code{TRUE} to enable strict type checking.} \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}{[\code{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}/\code{check_character} return a string with the error message. The function \code{expect_character} always returns an \code{\link[testthat]{expectation}}. } \description{ To check for scalar strings, see \code{\link{checkString}}. } \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{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkFunction.Rd0000644000176200001440000000730014646134410016026 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}{[\code{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}/\code{check_function} return 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{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkLogical.Rd0000644000176200001440000001236014646134410015615 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, typed.missing = FALSE, null.ok = FALSE ) check_logical( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE ) assertLogical( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, typed.missing = FALSE, 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, typed.missing = FALSE, 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, typed.missing = FALSE, null.ok = FALSE ) test_logical( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE ) expect_logical( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, typed.missing = FALSE, 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 no non-missing values allowed? Default is \code{TRUE}. Note that empty vectors do not have non-missing values.} \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{typed.missing}{[\code{logical(1)}]\cr If set to \code{FALSE} (default), all types of missing values (\code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_character_} or \code{NA_character_}) as well as empty vectors are allowed while type-checking atomic input. Set to \code{TRUE} to enable strict type checking.} \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}{[\code{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}/\code{check_logical} return 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{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomic}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkInteger}()}, \code{\link{checkIntegerish}()}, \code{\link{checkList}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkClass.Rd0000644000176200001440000000622614245411067015315 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}}. \code{x} must inherit from all specified classes.} \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}{[\code{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}/\code{check_class} return 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{ Other attributes: \code{\link{checkMultiClass}()}, \code{\link{checkNamed}()}, \code{\link{checkNames}()} Other classes: \code{\link{checkMultiClass}()}, \code{\link{checkR6}()} } \concept{attributes} \concept{classes} checkmate/man/checkmate-package.Rd0000644000176200001440000000673014423162567016575 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{ 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. } \section{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}}} } } \section{Check vectors}{ \itemize{ \item{\code{\link{checkLogical}}} \item{\code{\link{checkNumeric}}} \item{\code{\link{checkDouble}}} \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{checkPOSIXct}}} \item{\code{\link{checkVector}}} \item{\code{\link{checkAtomic}}} \item{\code{\link{checkAtomicVector}}} \item{\code{\link{checkRaw}}} } } \section{Check attributes}{ \itemize{ \item{\code{\link{checkClass}}} \item{\code{\link{checkMultiClass}}} \item{\code{\link{checkNames}}} \item{\code{\link{checkNamed}}} (deprecated) } } \section{Check compound types}{ \itemize{ \item{\code{\link{checkArray}}} \item{\code{\link{checkDataFrame}}} \item{\code{\link{checkMatrix}}} } } \section{Check other built-in R types}{ \itemize{ \item{\code{\link{checkDate}}} \item{\code{\link{checkEnvironment}}} \item{\code{\link{checkFunction}}} \item{\code{\link{checkFormula}}} \item{\code{\link{checkNull}}} } } \section{Check sets}{ \itemize{ \item{\code{\link{checkChoice}}} \item{\code{\link{checkSubset}}} \item{\code{\link{checkSetEqual}}} \item{\code{\link{checkDisjunct}}} \item{\code{\link{checkPermutation}}} } } \section{File IO}{ \itemize{ \item{\code{\link{checkFileExists}}} \item{\code{\link{checkDirectoryExists}}} \item{\code{\link{checkPathForOutput}}} \item{\code{\link{checkAccess}}} } } \section{Popular data types of third party packages}{ \itemize{ \item{\code{\link{checkDataTable}}} \item{\code{\link{checkR6}}} \item{\code{\link{checkTibble}}} } } \section{Safe coercion to integer}{ \itemize{ \item{\code{\link{asCount}}} \item{\code{\link{asInt}}} \item{\code{\link{asInteger}}} } } \section{Quick argument checks using a DSL}{ \itemize{ \item{\code{\link{qassert}}} \item{\code{\link{qassertr}}} } } \section{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://mllg.github.io/checkmate/} \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} (\href{https://orcid.org/0000-0001-9754-0393}{ORCID}) Other contributors: \itemize{ \item Bernd Bischl \email{bernd_bischl@gmx.net} [contributor] \item Dénes Tóth \email{toth.denes@kogentum.hu} (\href{https://orcid.org/0000-0003-4262-3217}{ORCID}) [contributor] } } checkmate/man/checkFALSE.Rd0000644000176200001440000000317514245411067015102 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.}/\code{check_false.} return 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/checkCount.Rd0000644000176200001440000000726014646134410015336 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, coerce = FALSE, .var.name = vname(x), add = NULL ) assert_count( x, na.ok = FALSE, positive = FALSE, tol = sqrt(.Machine$double.eps), null.ok = FALSE, coerce = 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{coerce}{[\code{logical(1)}]\cr If \code{TRUE}, the input \code{x} is returned as integer after an successful assertion.} \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}{[\code{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}/\code{check_count} return 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{checkScalar}()}, \code{\link{checkScalarNA}()}, \code{\link{checkString}()} } \concept{scalars} checkmate/DESCRIPTION0000644000176200001440000000522614651705516013723 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: 2.3.2 Authors@R: c( person("Michel", "Lang", NULL, "michellang@gmail.com", role = c("cre", "aut"), comment = c(ORCID = "0000-0001-9754-0393")), person("Bernd", "Bischl", NULL, "bernd_bischl@gmx.net", role = "ctb"), person("Dénes", "Tóth", NULL, "toth.denes@kogentum.hu", role = "ctb", comment = c(ORCID = "0000-0003-4262-3217")) ) URL: https://mllg.github.io/checkmate/, 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, fastmatch, data.table (>= 1.9.8), devtools, ggplot2, knitr, magrittr, microbenchmark, rmarkdown, testthat (>= 3.0.4), tinytest (>= 1.1.0), tibble License: BSD_3_clause + file LICENSE VignetteBuilder: knitr RoxygenNote: 7.3.2 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' 'checkCharacter.R' 'checkChoice.R' 'checkClass.R' 'checkComplex.R' 'checkCount.R' 'checkDataFrame.R' 'checkDataTable.R' 'checkDate.R' 'checkDirectoryExists.R' 'checkDisjunct.R' 'checkDouble.R' 'checkEnvironment.R' 'checkFALSE.R' 'checkFactor.R' 'checkFileExists.R' 'checkFlag.R' 'checkFormula.R' 'checkFunction.R' 'checkInt.R' 'checkInteger.R' 'checkIntegerish.R' 'checkList.R' 'checkLogical.R' 'checkMatrix.R' 'checkMultiClass.R' 'checkNamed.R' 'checkNames.R' 'checkNull.R' 'checkNumber.R' 'checkNumeric.R' 'checkOS.R' 'checkPOSIXct.R' 'checkPathForOutput.R' 'checkPermutation.R' 'checkR6.R' 'checkRaw.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: 2024-07-29 09:26:26 UTC; michel Author: Michel Lang [cre, aut] (), Bernd Bischl [ctb], Dénes Tóth [ctb] () Maintainer: Michel Lang Repository: CRAN Date/Publication: 2024-07-29 12:30:06 UTC