checkmate/0000755000176200001440000000000013616662435012212 5ustar liggesuserscheckmate/NAMESPACE0000644000176200001440000002173613616105461013431 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(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_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(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_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_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(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_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(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/LICENSE0000644000176200001440000000005113616076131013203 0ustar liggesusersYEAR: 2019 COPYRIGHT HOLDER: Michel Lang checkmate/README.md0000644000176200001440000000400213616076131013455 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/r/mllg/checkmate?branch=master) [![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/man/0000755000176200001440000000000013616076131012755 5ustar liggesuserscheckmate/man/checkFormula.Rd0000644000176200001440000000547013616076131015655 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}{[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} returns 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{checkAtomicVector}()}, \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{checkFunction}()}, \code{\link{checkIntegerish}()}, \code{\link{checkInteger}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkSubset.Rd0000644000176200001440000000631313616076131015512 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkSubset.R \name{checkSubset} \alias{checkSubset} \alias{check_subset} \alias{assertSubset} \alias{assert_subset} \alias{testSubset} \alias{test_subset} \alias{expect_subset} \title{Check if an argument is a subset of a given set} \usage{ checkSubset(x, choices, empty.ok = TRUE, fmatch = FALSE) check_subset(x, choices, empty.ok = TRUE, fmatch = FALSE) assertSubset( x, choices, empty.ok = TRUE, fmatch = FALSE, .var.name = vname(x), add = NULL ) assert_subset( x, choices, empty.ok = TRUE, fmatch = FALSE, .var.name = vname(x), add = NULL ) testSubset(x, choices, empty.ok = TRUE, fmatch = FALSE) test_subset(x, choices, empty.ok = TRUE, fmatch = FALSE) expect_subset( x, choices, empty.ok = TRUE, fmatch = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{choices}{[\code{atomic}]\cr Set of possible values. May be empty.} \item{empty.ok}{[\code{logical(1)}]\cr Treat zero-length \code{x} as subset of any set \code{choices} (this includes \code{NULL})? Default is \code{TRUE}.} \item{fmatch}{[\code{logical(1)}]\cr Use the set operations implemented in \code{\link[fastmatch]{fmatch}} in package \pkg{fastmatch}. If \pkg{fastmatch} is not installed, this silently falls back to \code{\link[base]{match}}. \code{\link[fastmatch]{fmatch}} modifies \code{y} by reference: A hash table is added as attribute which is used in subsequent calls.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertSubset}/\code{assert_subset} return \code{x} invisibly, whereas \code{checkSubset}/\code{check_subset} and \code{testSubset}/\code{test_subset} return \code{TRUE}. If the check is not successful, \code{assertSubset}/\code{assert_subset} throws an error message, \code{testSubset}/\code{test_subset} returns \code{FALSE}, and \code{checkSubset} returns a string with the error message. The function \code{expect_subset} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a subset of a given set } \note{ The object \code{x} must be of the same type as the set w.r.t. \code{\link[base]{typeof}}. Integers and doubles are both treated as numeric. } \examples{ testSubset(c("a", "z"), letters) testSubset("ab", letters) testSubset("Species", names(iris)) # x is not converted before the comparison (except for numerics) testSubset(factor("a"), "a") testSubset(1, "1") testSubset(1, as.integer(1)) } \seealso{ Other set: \code{\link{checkChoice}()}, \code{\link{checkDisjunct}()}, \code{\link{checkSetEqual}()} } \concept{set} checkmate/man/checkIntegerish.Rd0000644000176200001440000001430413616076131016345 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkIntegerish.R \name{checkIntegerish} \alias{checkIntegerish} \alias{check_integerish} \alias{assertIntegerish} \alias{assert_integerish} \alias{testIntegerish} \alias{test_integerish} \alias{expect_integerish} \title{Check if an object is an integerish vector} \usage{ checkIntegerish( x, tol = sqrt(.Machine$double.eps), lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE ) check_integerish( x, tol = sqrt(.Machine$double.eps), lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE ) assertIntegerish( x, tol = sqrt(.Machine$double.eps), lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, 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, 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, null.ok = FALSE ) test_integerish( x, tol = sqrt(.Machine$double.eps), lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE ) expect_integerish( x, tol = sqrt(.Machine$double.eps), lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{tol}{[\code{double(1)}]\cr Numerical tolerance used to check whether a double or complex can be converted. Default is \code{sqrt(.Machine$double.eps)}.} \item{lower}{[\code{numeric(1)}]\cr Lower value all elements of \code{x} must be greater than 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 only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{sorted}{[\code{logical(1)}]\cr Elements must be sorted in ascending order. Missing values are ignored.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{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}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertIntegerish}/\code{assert_integerish} return \code{x} invisibly, whereas \code{checkIntegerish}/\code{check_integerish} and \code{testIntegerish}/\code{test_integerish} return \code{TRUE}. If the check is not successful, \code{assertIntegerish}/\code{assert_integerish} throws an error message, \code{testIntegerish}/\code{test_integerish} returns \code{FALSE}, and \code{checkIntegerish} returns a string with the error message. The function \code{expect_integerish} always returns an \code{\link[testthat]{expectation}}. } \description{ An integerish value is defined as value safely convertible to integer. This includes integers and numeric values which are close to an integer w.r.t. a numeric tolerance. } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \note{ To convert from integerish to integer, use \code{\link{asInteger}}. } \examples{ testIntegerish(1L) testIntegerish(1.) testIntegerish(1:2, lower = 1L, upper = 2L, any.missing = FALSE) } \seealso{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkAtomic}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{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/checkMultiClass.Rd0000644000176200001440000000540013616076131016321 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}{[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} returns 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/makeAssertion.Rd0000644000176200001440000000604113616076131016052 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/checkNamed.Rd0000644000176200001440000000436113616076131015272 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkNamed.R \name{checkNamed} \alias{checkNamed} \alias{check_named} \alias{assertNamed} \alias{assert_named} \alias{testNamed} \alias{test_named} \title{Check if an argument is named} \usage{ checkNamed(x, type = "named") check_named(x, type = "named") assertNamed(x, type = "named", .var.name = vname(x), add = NULL) assert_named(x, type = "named", .var.name = vname(x), add = NULL) testNamed(x, type = "named") test_named(x, type = "named") } \arguments{ \item{x}{[any]\cr Object to check.} \item{type}{[character(1)]\cr Select the check(s) to perform. \dQuote{unnamed} checks \code{x} to be unnamed. \dQuote{named} (default) checks \code{x} to be named which excludes names to be \code{NA} or empty (\code{""}). \dQuote{unique} additionally tests for non-duplicated names. \dQuote{strict} checks for unique names which comply to R's variable name restrictions. Note that for zero-length \code{x} every name check evaluates to \code{TRUE}.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertNamed}/\code{assert_named} return \code{x} invisibly, whereas \code{checkNamed}/\code{check_named} and \code{testNamed}/\code{test_named} return \code{TRUE}. If the check is not successful, \code{assertNamed}/\code{assert_named} throws an error message, \code{testNamed}/\code{test_named} returns \code{FALSE}, and \code{checkNamed} returns a string with the error message. The function \code{expect_named} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is named } \note{ These function are deprecated and will be removed in a future version. Please use \code{\link{checkNames}} instead. } \examples{ x = 1:3 testNamed(x, "unnamed") names(x) = letters[1:3] testNamed(x, "unique") } \seealso{ Other attributes: \code{\link{checkClass}()}, \code{\link{checkMultiClass}()}, \code{\link{checkNames}()} } \concept{attributes} checkmate/man/checkList.Rd0000644000176200001440000001361013616076131015156 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkList.R \name{checkList} \alias{checkList} \alias{check_list} \alias{assertList} \alias{assert_list} \alias{testList} \alias{test_list} \alias{expect_list} \title{Check if an argument is a list} \usage{ checkList( x, types = character(0L), any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE ) check_list( x, types = character(0L), any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE ) assertList( x, types = character(0L), any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_list( x, types = character(0L), any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) testList( x, types = character(0L), any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE ) test_list( x, types = character(0L), any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE ) expect_list( x, types = character(0L), any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{types}{[\code{character}]\cr Character vector of class names. Each list element must inherit from at least one of the provided types. The types \dQuote{logical}, \dQuote{integer}, \dQuote{integerish}, \dQuote{double}, \dQuote{numeric}, \dQuote{complex}, \dQuote{character}, \dQuote{factor}, \dQuote{atomic}, \dQuote{vector} \dQuote{atomicvector}, \dQuote{array}, \dQuote{matrix}, \dQuote{list}, \dQuote{function}, \dQuote{environment} and \dQuote{null} are supported. For other types \code{\link[base]{inherits}} is used as a fallback to check \code{x}'s inheritance. Defaults to \code{character(0)} (no check).} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertList}/\code{assert_list} return \code{x} invisibly, whereas \code{checkList}/\code{check_list} and \code{testList}/\code{test_list} return \code{TRUE}. If the check is not successful, \code{assertList}/\code{assert_list} throws an error message, \code{testList}/\code{test_list} returns \code{FALSE}, and \code{checkList} returns a string with the error message. The function \code{expect_list} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a list } \note{ Contrary to R's \code{\link[base]{is.list}}, objects of type \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{checkAtomicVector}()}, \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{checkIntegerish}()}, \code{\link{checkInteger}()}, \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/anyMissing.Rd0000644000176200001440000000252013616076131015364 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/allMissing.R, R/anyMissing.R \name{allMissing} \alias{allMissing} \alias{anyMissing} \title{Check if an object contains missing values} \usage{ allMissing(x) anyMissing(x) } \arguments{ \item{x}{[\code{ANY}]\cr Object to check.} } \value{ [\code{logical(1)}] Returns \code{TRUE} if any (\code{anyMissing}) or all (\code{allMissing}) elements of \code{x} are missing (see details), \code{FALSE} otherwise. } \description{ Supported are atomic types (see \code{\link[base]{is.atomic}}), lists and data frames. Missingness is defined as \code{NA} or \code{NaN} for atomic types and data frame columns, \code{NULL} is defined as missing for lists.\cr \code{allMissing} applied to a \code{data.frame} returns \code{TRUE} if at least one column has only non-missing values. If you want to perform the less frequent check that there is not a single non-missing observation present in the \code{data.frame}, use \code{all(sapply(df, allMissing))} instead. } \examples{ allMissing(1:2) allMissing(c(1, NA)) allMissing(c(NA, NA)) x = data.frame(a = 1:2, b = NA) # Note how allMissing combines the results for data frames: allMissing(x) all(sapply(x, allMissing)) anyMissing(c(1, 1)) anyMissing(c(1, NA)) anyMissing(list(1, NULL)) x = iris x[, "Species"] = NA anyMissing(x) allMissing(x) } checkmate/man/checkR6.Rd0000644000176200001440000000710213616076131014531 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkR6.R \name{checkR6} \alias{checkR6} \alias{check_r6} \alias{assertR6} \alias{assert_r6} \alias{testR6} \alias{test_r6} \alias{expect_r6} \title{Check if an argument is a R6 class} \usage{ checkR6( x, classes = NULL, ordered = FALSE, cloneable = NULL, public = NULL, private = NULL, null.ok = FALSE ) check_r6( x, classes = NULL, ordered = FALSE, cloneable = NULL, public = NULL, private = NULL, null.ok = FALSE ) assertR6( x, classes = NULL, ordered = FALSE, cloneable = NULL, public = NULL, private = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_r6( x, classes = NULL, ordered = FALSE, cloneable = NULL, public = NULL, private = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) testR6( x, classes = NULL, ordered = FALSE, cloneable = NULL, public = NULL, private = NULL, null.ok = FALSE ) test_r6( x, classes = NULL, ordered = FALSE, cloneable = NULL, public = NULL, private = NULL, null.ok = FALSE ) expect_r6( x, classes = NULL, ordered = FALSE, cloneable = NULL, public = NULL, private = NULL, null.ok = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{classes}{[\code{character}]\cr Class names to check for inheritance with \code{\link[base]{inherits}}. \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}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertClass}/\code{assert_class} return \code{x} invisibly, whereas \code{checkClass}/\code{check_class} and \code{testClass}/\code{test_class} return \code{TRUE}. If the check is not successful, \code{assertClass}/\code{assert_class} throws an error message, \code{testClass}/\code{test_class} returns \code{FALSE}, and \code{checkClass} returns a string with the error message. The function \code{expect_class} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a R6 class } \examples{ library(R6) generator = R6Class("Bar", public = list(a = 5), private = list(b = 42), active = list(c = function() 99) ) x = generator$new() checkR6(x, "Bar", cloneable = TRUE, public = "a") } \seealso{ Other classes: \code{\link{checkClass}()}, \code{\link{checkMultiClass}()} } \concept{classes} checkmate/man/checkAtomicVector.Rd0000644000176200001440000001147113616076131016645 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkAtomicVector.R \name{checkAtomicVector} \alias{checkAtomicVector} \alias{check_atomic_vector} \alias{assertAtomicVector} \alias{assert_atomic_vector} \alias{testAtomicVector} \alias{test_atomic_vector} \alias{expect_atomic_vector} \title{Check that an argument is an atomic vector} \usage{ checkAtomicVector( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL ) check_atomic_vector( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL ) assertAtomicVector( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, .var.name = vname(x), add = NULL ) assert_atomic_vector( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, .var.name = vname(x), add = NULL ) testAtomicVector( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL ) test_atomic_vector( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL ) expect_atomic_vector( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertAtomicVector}/\code{assert_atomic_vector} return \code{x} invisibly, whereas \code{checkAtomicVector}/\code{check_atomic_vector} and \code{testAtomicVector}/\code{test_atomic_vector} return \code{TRUE}. If the check is not successful, \code{assertAtomicVector}/\code{assert_atomic_vector} throws an error message, \code{testAtomicVector}/\code{test_atomic_vector} returns \code{FALSE}, and \code{checkAtomicVector} returns a string with the error message. The function \code{expect_atomic_vector} always returns an \code{\link[testthat]{expectation}}. } \description{ An atomic vector is defined slightly different from specifications in \code{\link[base]{is.atomic}} and \code{\link[base]{is.vector}}: An atomic vector is either \code{logical}, \code{integer}, \code{numeric}, \code{complex}, \code{character} or \code{raw} and can have any attributes except a dimension attribute (like matrices). I.e., a \code{factor} is an atomic vector, but a matrix or \code{NULL} are not. In short, this is 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{checkIntegerish}()}, \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}()} Other atomicvector: \code{\link{checkAtomic}()}, \code{\link{checkVector}()} } \concept{atomicvector} \concept{basetypes} checkmate/man/anyNaN.Rd0000644000176200001440000000076413616076131014437 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/checkAtomic.Rd0000644000176200001440000001045513616076131015463 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkAtomic.R \name{checkAtomic} \alias{checkAtomic} \alias{check_atomic} \alias{assertAtomic} \alias{assert_atomic} \alias{testAtomic} \alias{test_atomic} \alias{expect_atomic} \title{Check that an argument is an atomic vector} \usage{ checkAtomic( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL ) check_atomic( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL ) assertAtomic( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, .var.name = vname(x), add = NULL ) assert_atomic( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, .var.name = vname(x), add = NULL ) testAtomic( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL ) test_atomic( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL ) expect_atomic( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertAtomic}/\code{assert_atomic} return \code{x} invisibly, whereas \code{checkAtomic}/\code{check_atomic} and \code{testAtomic}/\code{test_atomic} return \code{TRUE}. If the check is not successful, \code{assertAtomic}/\code{assert_atomic} throws an error message, \code{testAtomic}/\code{test_atomic} returns \code{FALSE}, and \code{checkAtomic} returns a string with the error message. The function \code{expect_atomic} always returns an \code{\link[testthat]{expectation}}. } \description{ For the definition of \dQuote{atomic}, see \code{\link[base]{is.atomic}}. } \examples{ testAtomic(letters, min.len = 1L, any.missing = FALSE) } \seealso{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkIntegerish}()}, \code{\link{checkInteger}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} Other atomicvector: \code{\link{checkAtomicVector}()}, \code{\link{checkVector}()} } \concept{atomicvector} \concept{basetypes} checkmate/man/checkInteger.Rd0000644000176200001440000001260313616076131015641 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkInteger.R \name{checkInteger} \alias{checkInteger} \alias{check_integer} \alias{assertInteger} \alias{assert_integer} \alias{testInteger} \alias{test_integer} \alias{expect_integer} \title{Check if an argument is vector of type integer} \usage{ checkInteger( x, lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE ) check_integer( x, lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE ) assertInteger( x, lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_integer( x, lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) testInteger( x, lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE ) test_integer( x, lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE ) expect_integer( x, lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{lower}{[\code{numeric(1)}]\cr Lower value all elements of \code{x} must be greater than 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 only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{sorted}{[\code{logical(1)}]\cr Elements must be sorted in ascending order. Missing values are ignored.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertInteger}/\code{assert_integer} return \code{x} invisibly, whereas \code{checkInteger}/\code{check_integer} and \code{testInteger}/\code{test_integer} return \code{TRUE}. If the check is not successful, \code{assertInteger}/\code{assert_integer} throws an error message, \code{testInteger}/\code{test_integer} returns \code{FALSE}, and \code{checkInteger} returns a string with the error message. The function \code{expect_integer} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is vector of type integer } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testInteger(1L) testInteger(1.) testInteger(1:2, lower = 1, upper = 2, any.missing = FALSE) } \seealso{ \code{\link{asInteger}} Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkAtomic}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{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/checkDate.Rd0000644000176200001440000001107413616076131015122 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkDate.R \name{checkDate} \alias{checkDate} \alias{check_date} \alias{assertDate} \alias{assert_date} \alias{testDate} \alias{test_date} \alias{expect_date} \title{Check that an argument is a Date} \usage{ checkDate( x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, null.ok = FALSE ) check_date( x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, null.ok = FALSE ) assertDate( x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_date( x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL ) testDate( x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, null.ok = FALSE ) test_date( x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, null.ok = FALSE ) expect_date( x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, null.ok = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{lower}{[\code{\link[base]{Date}}]\cr All non-missing dates in \code{x} must be >= this date. Comparison is done via \code{\link[base]{Ops.Date}}.} \item{upper}{[\code{\link[base]{Date}}]\cr All non-missing dates in \code{x} must be before <= this date. Comparison is done via \code{\link[base]{Ops.Date}}.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertAtomic}/\code{assert_atomic} return \code{x} invisibly, whereas \code{checkAtomic}/\code{check_atomic} and \code{testAtomic}/\code{test_atomic} return \code{TRUE}. If the check is not successful, \code{assertAtomic}/\code{assert_atomic} throws an error message, \code{testAtomic}/\code{test_atomic} returns \code{FALSE}, and \code{checkAtomic} returns a string with the error message. The function \code{expect_atomic} always returns an \code{\link[testthat]{expectation}}. } \description{ Checks that an object is of class \code{\link[base]{Date}}. } \seealso{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkAtomic}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkIntegerish}()}, \code{\link{checkInteger}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkString.Rd0000644000176200001440000000755613616076131015525 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkString.R \name{checkString} \alias{checkString} \alias{check_string} \alias{assertString} \alias{assert_string} \alias{testString} \alias{test_string} \alias{expect_string} \title{Check if an argument is a string} \usage{ checkString( x, na.ok = FALSE, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE ) check_string( x, na.ok = FALSE, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE ) assertString( x, na.ok = FALSE, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_string( x, na.ok = FALSE, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL ) testString( x, na.ok = FALSE, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE ) test_string( x, na.ok = FALSE, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE ) expect_string( x, na.ok = FALSE, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{na.ok}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{FALSE}.} \item{min.chars}{[\code{integer(1)}]\cr Minimum number of characters for each element of \code{x}.} \item{pattern}{[\code{character(1L)}]\cr Regular expression as used in \code{\link[base]{grepl}}. All non-missing elements of \code{x} must comply to this pattern.} \item{fixed}{[\code{character(1)}]\cr Substring to detect in \code{x}. Will be used as \code{pattern} in \code{\link[base]{grepl}} with option \code{fixed} set to \code{TRUE}. All non-missing elements of \code{x} must contain this substring.} \item{ignore.case}{[\code{logical(1)}]\cr See \code{\link[base]{grepl}}. Default is \code{FALSE}.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertString}/\code{assert_string} return \code{x} invisibly, whereas \code{checkString}/\code{check_string} and \code{testString}/\code{test_string} return \code{TRUE}. If the check is not successful, \code{assertString}/\code{assert_string} throws an error message, \code{testString}/\code{test_string} returns \code{FALSE}, and \code{checkString} returns a string with the error message. The function \code{expect_string} always returns an \code{\link[testthat]{expectation}}. } \description{ A string is defined as a scalar character vector. } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testString("a") testString(letters) } \seealso{ Other scalars: \code{\link{checkCount}()}, \code{\link{checkFlag}()}, \code{\link{checkInt}()}, \code{\link{checkNumber}()}, \code{\link{checkScalarNA}()}, \code{\link{checkScalar}()} } \concept{scalars} checkmate/man/checkFALSE.Rd0000644000176200001440000000315013616076131015073 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkFALSE.R \name{checkFALSE} \alias{checkFALSE} \alias{check_false} \alias{assertFALSE} \alias{assert_false} \alias{testFALSE} \alias{test_false} \title{Check if an argument is FALSE} \usage{ checkFALSE(x, na.ok = FALSE) check_false(x, na.ok = FALSE) assertFALSE(x, na.ok = FALSE, .var.name = vname(x), add = NULL) assert_false(x, na.ok = FALSE, .var.name = vname(x), add = NULL) testFALSE(x, na.ok = FALSE) test_false(x, na.ok = FALSE) } \arguments{ \item{x}{[any]\cr Object to check.} \item{na.ok}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{FALSE}.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertFALSE.}/\code{assert_false.} return \code{x} invisibly, whereas \code{checkFALSE.}/\code{check_false.} and \code{testFALSE.}/\code{test_false.} return \code{TRUE}. If the check is not successful, \code{assertFALSE.}/\code{assert_false.} throws an error message, \code{testFALSE.}/\code{test_false.} returns \code{FALSE}, and \code{checkFALSE.} returns a string with the error message. The function \code{expect_false.} always returns an \code{\link[testthat]{expectation}}. } \description{ Simply checks if an argument is \code{FALSE}. } \examples{ testFALSE(FALSE) testFALSE(TRUE) } checkmate/man/makeTest.Rd0000644000176200001440000000374713616076131015034 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/checkDirectoryExists.Rd0000644000176200001440000000640013616076131017406 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkDirectoryExists.R \name{checkDirectoryExists} \alias{checkDirectoryExists} \alias{check_directory_exists} \alias{assertDirectoryExists} \alias{assert_directory_exists} \alias{testDirectoryExists} \alias{test_directory_exists} \alias{expect_directory_exists} \alias{checkDirectory} \alias{assertDirectory} \alias{assert_directory} \alias{testDirectory} \alias{test_directory} \alias{expect_directory} \title{Check for existence and access rights of directories} \usage{ checkDirectoryExists(x, access = "") check_directory_exists(x, access = "") assertDirectoryExists(x, access = "", .var.name = vname(x), add = NULL) assert_directory_exists(x, access = "", .var.name = vname(x), add = NULL) testDirectoryExists(x, access = "") test_directory_exists(x, access = "") expect_directory_exists(x, access = "", info = NULL, label = vname(x)) checkDirectory(x, access = "") assertDirectory(x, access = "", .var.name = vname(x), add = NULL) assert_directory(x, access = "", .var.name = vname(x), add = NULL) testDirectory(x, access = "") test_directory(x, access = "") expect_directory(x, access = "", info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{access}{[\code{character(1)}]\cr Single string containing possible characters \sQuote{r}, \sQuote{w} and \sQuote{x} to force a check for read, write or execute access rights, respectively. Write and executable rights are not checked on Windows.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertDirectoryExists}/\code{assert_directory_exists} return \code{x} invisibly, whereas \code{checkDirectoryExists}/\code{check_directory_exists} and \code{testDirectoryExists}/\code{test_directory_exists} return \code{TRUE}. If the check is not successful, \code{assertDirectoryExists}/\code{assert_directory_exists} throws an error message, \code{testDirectoryExists}/\code{test_directory_exists} returns \code{FALSE}, and \code{checkDirectoryExists} returns a string with the error message. The function \code{expect_directory_exists} always returns an \code{\link[testthat]{expectation}}. } \description{ Check for existence and access rights of directories } \note{ The functions without the suffix \dQuote{exists} are deprecated and will be removed from the package in a future version due to name clashes. } \examples{ # Is R's home directory readable? testDirectory(R.home(), "r") # Is R's home directory readable and writable? testDirectory(R.home(), "rw") } \seealso{ Other filesystem: \code{\link{checkAccess}()}, \code{\link{checkFileExists}()}, \code{\link{checkPathForOutput}()} } \concept{filesystem} checkmate/man/checkTibble.Rd0000644000176200001440000001301513616076131015443 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}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertTibble}/\code{assert_tibble} return \code{x} invisibly, whereas \code{checkTibble}/\code{check_tibble} and \code{testTibble}/\code{test_tibble} return \code{TRUE}. If the check is not successful, \code{assertTibble}/\code{assert_tibble} throws an error message, \code{testTibble}/\code{test_tibble} returns \code{FALSE}, and \code{checkTibble} returns a string with the error message. The function \code{expect_tibble} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a tibble } \examples{ library(tibble) x = as_tibble(iris) testTibble(x) testTibble(x, nrow = 150, any.missing = FALSE) } \seealso{ Other compound: \code{\link{checkArray}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDataTable}()}, \code{\link{checkMatrix}()} } \concept{compound} checkmate/man/checkAccess.Rd0000644000176200001440000000456613616076131015456 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkAccess.R \name{checkAccess} \alias{checkAccess} \alias{check_access} \alias{assertAccess} \alias{assert_access} \alias{testAccess} \alias{test_access} \alias{expect_access} \title{Check file system access rights} \usage{ checkAccess(x, access = "") check_access(x, access = "") assertAccess(x, access = "", .var.name = vname(x), add = NULL) assert_access(x, access = "", .var.name = vname(x), add = NULL) testAccess(x, access = "") test_access(x, access = "") expect_access(x, access = "", info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{access}{[\code{character(1)}]\cr Single string containing possible characters \sQuote{r}, \sQuote{w} and \sQuote{x} to force a check for read, write or execute access rights, respectively. Write and executable rights are not checked on Windows.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertAccess}/\code{assert_access} return \code{x} invisibly, whereas \code{checkAccess}/\code{check_access} and \code{testAccess}/\code{test_access} return \code{TRUE}. If the check is not successful, \code{assertAccess}/\code{assert_access} throws an error message, \code{testAccess}/\code{test_access} returns \code{FALSE}, and \code{checkAccess} returns a string with the error message. The function \code{expect_access} always returns an \code{\link[testthat]{expectation}}. } \description{ Check file system access rights } \examples{ # Is R's home directory readable? testAccess(R.home(), "r") # Is R's home directory writeable? testAccess(R.home(), "w") } \seealso{ Other filesystem: \code{\link{checkDirectoryExists}()}, \code{\link{checkFileExists}()}, \code{\link{checkPathForOutput}()} } \concept{filesystem} checkmate/man/checkScalar.Rd0000644000176200001440000000531013616076131015446 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkScalar.R \name{checkScalar} \alias{checkScalar} \alias{check_scalar} \alias{assertScalar} \alias{assert_scalar} \alias{testScalar} \alias{test_scalar} \alias{expect_scalar} \title{Check if an argument is a single atomic value} \usage{ checkScalar(x, na.ok = FALSE, null.ok = FALSE) check_scalar(x, na.ok = FALSE, null.ok = FALSE) assertScalar( x, na.ok = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_scalar( x, na.ok = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL ) testScalar(x, na.ok = FALSE, null.ok = FALSE) test_scalar(x, na.ok = FALSE, null.ok = FALSE) expect_scalar(x, na.ok = FALSE, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{na.ok}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{FALSE}.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertScalar}/\code{assert_scalar} return \code{x} invisibly, whereas \code{checkScalar}/\code{check_scalar} and \code{testScalar}/\code{test_scalar} return \code{TRUE}. If the check is not successful, \code{assertScalar}/\code{assert_scalar} throws an error message, \code{testScalar}/\code{test_scalar} returns \code{FALSE}, and \code{checkScalar} returns a string with the error message. The function \code{expect_scalar} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a single atomic value } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testScalar(1) testScalar(1:10) } \seealso{ Other scalars: \code{\link{checkCount}()}, \code{\link{checkFlag}()}, \code{\link{checkInt}()}, \code{\link{checkNumber}()}, \code{\link{checkScalarNA}()}, \code{\link{checkString}()} } \concept{scalars} checkmate/man/checkComplex.Rd0000644000176200001440000001122513616076131015652 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkComplex.R \name{checkComplex} \alias{checkComplex} \alias{check_complex} \alias{assertComplex} \alias{assert_complex} \alias{testComplex} \alias{test_complex} \alias{expect_complex} \title{Check if an argument is a vector of type complex} \usage{ checkComplex( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE ) check_complex( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE ) assertComplex( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_complex( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) testComplex( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE ) test_complex( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE ) expect_complex( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertComplex}/\code{assert_complex} return \code{x} invisibly, whereas \code{checkComplex}/\code{check_complex} and \code{testComplex}/\code{test_complex} return \code{TRUE}. If the check is not successful, \code{assertComplex}/\code{assert_complex} throws an error message, \code{testComplex}/\code{test_complex} returns \code{FALSE}, and \code{checkComplex} returns a string with the error message. The function \code{expect_complex} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a vector of type complex } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testComplex(1) testComplex(1+1i) } \seealso{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkAtomic}()}, \code{\link{checkCharacter}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkIntegerish}()}, \code{\link{checkInteger}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/matchArg.Rd0000644000176200001440000000212613616076131014773 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/checkPOSIXct.Rd0000644000176200001440000001157413616076131015503 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkPOSIXct.R \name{checkPOSIXct} \alias{checkPOSIXct} \alias{check_posixct} \alias{assertPOSIXct} \alias{assert_posixct} \alias{testPOSIXct} \alias{test_posixct} \alias{expect_posixct} \title{Check that an argument is a date/time object in POSIXct format} \usage{ checkPOSIXct( x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, null.ok = FALSE ) check_posixct( x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, null.ok = FALSE ) assertPOSIXct( x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_posixct( x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL ) testPOSIXct( x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, null.ok = FALSE ) test_posixct( x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, null.ok = FALSE ) expect_posixct( x, lower = NULL, upper = NULL, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, null.ok = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{lower}{[\code{\link[base]{Date}}]\cr All non-missing dates in \code{x} must be >= this POSIXct time. Must be provided in the same timezone as \code{x}.} \item{upper}{[\code{\link[base]{Date}}]\cr All non-missing dates in \code{x} must be <= this POSIXct time. Must be provided in the same timezone as \code{x}.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{sorted}{[\code{logical(1)}]\cr Elements must be sorted in ascending order. Missing values are ignored.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertAtomic}/\code{assert_atomic} return \code{x} invisibly, whereas \code{checkAtomic}/\code{check_atomic} and \code{testAtomic}/\code{test_atomic} return \code{TRUE}. If the check is not successful, \code{assertAtomic}/\code{assert_atomic} throws an error message, \code{testAtomic}/\code{test_atomic} returns \code{FALSE}, and \code{checkAtomic} returns a string with the error message. The function \code{expect_atomic} always returns an \code{\link[testthat]{expectation}}. } \description{ Checks that an object is of class \code{\link[base]{POSIXct}}. } \seealso{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkAtomic}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkIntegerish}()}, \code{\link{checkInteger}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkOS.Rd0000644000176200001440000000343513616076131014570 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkOS.R \name{checkOS} \alias{checkOS} \alias{check_os} \alias{assertOS} \alias{assert_os} \alias{testOS} \alias{test_os} \alias{expect_os} \title{Check the operating system} \usage{ checkOS(os) check_os(os) assertOS(os, add = NULL, .var.name = NULL) assert_os(os, add = NULL, .var.name = NULL) testOS(os) test_os(os) expect_os(os, info = NULL, label = NULL) } \arguments{ \item{os}{[\code{character(1)}]\cr Check the operating system to be in a set with possible elements \dQuote{windows}, \dQuote{mac}, \dQuote{linux} and \dQuote{solaris}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertOS}/\code{assert_os} return \code{x} invisibly, whereas \code{checkOS}/\code{check_os} and \code{testOS}/\code{test_os} return \code{TRUE}. If the check is not successful, \code{assertOS}/\code{assert_os} throws an error message, \code{testOS}/\code{test_os} returns \code{FALSE}, and \code{checkOS} returns a string with the error message. The function \code{expect_os} always returns an \code{\link[testthat]{expectation}}. } \description{ Check the operating system } \examples{ testOS("linux") } checkmate/man/checkVector.Rd0000644000176200001440000001064013616076131015505 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 only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertVector}/\code{assert_vector} return \code{x} invisibly, whereas \code{checkVector}/\code{check_vector} and \code{testVector}/\code{test_vector} return \code{TRUE}. If the check is not successful, \code{assertVector}/\code{assert_vector} throws an error message, \code{testVector}/\code{test_vector} returns \code{FALSE}, and \code{checkVector} returns a string with the error message. The function \code{expect_vector} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a vector } \examples{ testVector(letters, min.len = 1L, any.missing = FALSE) } \seealso{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkAtomic}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkIntegerish}()}, \code{\link{checkInteger}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()} Other atomicvector: \code{\link{checkAtomicVector}()}, \code{\link{checkAtomic}()} } \concept{atomicvector} \concept{basetypes} checkmate/man/checkRaw.Rd0000644000176200001440000000720613616076131015000 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}{[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} returns 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{checkAtomicVector}()}, \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{checkIntegerish}()}, \code{\link{checkInteger}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkDisjunct.Rd0000644000176200001440000000554113616076131016032 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}{[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} returns 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{checkSetEqual}()}, \code{\link{checkSubset}()} } \concept{set} checkmate/man/checkEnvironment.Rd0000644000176200001440000000644513616076131016557 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkEnvironment.R \name{checkEnvironment} \alias{checkEnvironment} \alias{check_environment} \alias{assertEnvironment} \alias{assert_environment} \alias{testEnvironment} \alias{test_environment} \alias{expect_environment} \title{Check if an argument is an environment} \usage{ checkEnvironment(x, contains = character(0L), null.ok = FALSE) check_environment(x, contains = character(0L), null.ok = FALSE) assertEnvironment( x, contains = character(0L), null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_environment( x, contains = character(0L), null.ok = FALSE, .var.name = vname(x), add = NULL ) testEnvironment(x, contains = character(0L), null.ok = FALSE) test_environment(x, contains = character(0L), null.ok = FALSE) expect_environment( x, contains = character(0L), null.ok = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{contains}{[\code{character}]\cr Vector of object names expected in the environment. Defaults to \code{character(0)}.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertEnvironment}/\code{assert_environment} return \code{x} invisibly, whereas \code{checkEnvironment}/\code{check_environment} and \code{testEnvironment}/\code{test_environment} return \code{TRUE}. If the check is not successful, \code{assertEnvironment}/\code{assert_environment} throws an error message, \code{testEnvironment}/\code{test_environment} returns \code{FALSE}, and \code{checkEnvironment} returns a string with the error message. The function \code{expect_environment} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is an environment } \examples{ ee = as.environment(list(a = 1)) testEnvironment(ee) testEnvironment(ee, contains = "a") } \seealso{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkAtomic}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkIntegerish}()}, \code{\link{checkInteger}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkCount.Rd0000644000176200001440000000722513616076131015340 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}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertCount}/\code{assert_count} return \code{x} invisibly, whereas \code{checkCount}/\code{check_count} and \code{testCount}/\code{test_count} return \code{TRUE}. If the check is not successful, \code{assertCount}/\code{assert_count} throws an error message, \code{testCount}/\code{test_count} returns \code{FALSE}, and \code{checkCount} returns a string with the error message. The function \code{expect_count} always returns an \code{\link[testthat]{expectation}}. } \description{ A count is defined as non-negative integerish value. } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \note{ To perform an assertion and then convert to integer, use \code{\link{asCount}}. \code{assertCount} will not convert numerics to integer. } \examples{ testCount(1) testCount(-1) } \seealso{ Other scalars: \code{\link{checkFlag}()}, \code{\link{checkInt}()}, \code{\link{checkNumber}()}, \code{\link{checkScalarNA}()}, \code{\link{checkScalar}()}, \code{\link{checkString}()} } \concept{scalars} checkmate/man/checkNumber.Rd0000644000176200001440000000660213616076131015476 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}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertNumber}/\code{assert_number} return \code{x} invisibly, whereas \code{checkNumber}/\code{check_number} and \code{testNumber}/\code{test_number} return \code{TRUE}. If the check is not successful, \code{assertNumber}/\code{assert_number} throws an error message, \code{testNumber}/\code{test_number} returns \code{FALSE}, and \code{checkNumber} returns a string with the error message. The function \code{expect_number} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a single numeric value } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testNumber(1) testNumber(1:2) } \seealso{ Other scalars: \code{\link{checkCount}()}, \code{\link{checkFlag}()}, \code{\link{checkInt}()}, \code{\link{checkScalarNA}()}, \code{\link{checkScalar}()}, \code{\link{checkString}()} } \concept{scalars} checkmate/man/qassertr.Rd0000644000176200001440000000364313616076131015116 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/qassertr.R \name{qassertr} \alias{qassertr} \alias{qtestr} \alias{qexpectr} \title{Quick recursive arguments checks on lists and data frames} \usage{ qassertr(x, rules, .var.name = vname(x)) qtestr(x, rules, depth = 1L) qexpectr(x, rules, info = NULL, label = vname(x)) } \arguments{ \item{x}{[\code{list} or \code{data.frame}]\cr List or data frame to check for compliance with at least one of \code{rules}. See details of \code{\link{qtest}} for rule explanation.} \item{rules}{[\code{character}]\cr Set of rules. See \code{\link{qtest}}} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in error messages. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{depth}{[\code{integer(1)}]\cr Maximum recursion depth. Defaults to \dQuote{1} to directly check list elements or data frame columns. Set to a higher value to check lists of lists of elements.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ See \code{\link{qassert}}. } \description{ These functions are the tuned counterparts of \code{\link{qtest}}, \code{\link{qassert}} and \code{\link{qexpect}} tailored for recursive checks of list elements or data frame columns. } \examples{ # All list elements are integers with length >= 1? qtestr(as.list(1:10), "i+") # All list elements (i.e. data frame columns) are numeric? qtestr(iris, "n") # All list elements are numeric, w/o NAs? qtestr(list(a = 1:3, b = rnorm(1), c = letters), "N+") # All list elements are numeric OR character qtestr(list(a = 1:3, b = rnorm(1), c = letters), c("N+", "S+")) } \seealso{ \code{\link{qtest}}, \code{\link{qassert}} } checkmate/man/checkDataFrame.Rd0000644000176200001440000001442413616076131016073 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}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertDataFrame}/\code{assert_data_frame} return \code{x} invisibly, whereas \code{checkDataFrame}/\code{check_data_frame} and \code{testDataFrame}/\code{test_data_frame} return \code{TRUE}. If the check is not successful, \code{assertDataFrame}/\code{assert_data_frame} throws an error message, \code{testDataFrame}/\code{test_data_frame} returns \code{FALSE}, and \code{checkDataFrame} returns a string with the error message. The function \code{expect_data_frame} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a data frame } \examples{ testDataFrame(iris) testDataFrame(iris, types = c("numeric", "factor"), min.rows = 1, col.names = "named") } \seealso{ Other compound: \code{\link{checkArray}()}, \code{\link{checkDataTable}()}, \code{\link{checkMatrix}()}, \code{\link{checkTibble}()} Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkAtomic}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkIntegerish}()}, \code{\link{checkInteger}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} \concept{compound} checkmate/man/register_test_backend.Rd0000644000176200001440000000127313616076131017601 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/checkSetEqual.Rd0000644000176200001440000000626113616076131015772 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkSetEqual.R \name{checkSetEqual} \alias{checkSetEqual} \alias{check_set_equal} \alias{assertSetEqual} \alias{assert_set_equal} \alias{testSetEqual} \alias{test_set_equal} \alias{expect_set_equal} \title{Check if an argument is equal to a given set} \usage{ checkSetEqual(x, y, ordered = FALSE, fmatch = FALSE) check_set_equal(x, y, ordered = FALSE, fmatch = FALSE) assertSetEqual( x, y, ordered = FALSE, fmatch = FALSE, .var.name = vname(x), add = NULL ) assert_set_equal( x, y, ordered = FALSE, fmatch = FALSE, .var.name = vname(x), add = NULL ) testSetEqual(x, y, ordered = FALSE, fmatch = FALSE) test_set_equal(x, y, ordered = FALSE, fmatch = FALSE) expect_set_equal( x, y, ordered = FALSE, fmatch = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{y}{[\code{atomic}]\cr Set to compare with.} \item{ordered}{[\code{logical(1)}]\cr Check \code{x} to have the same length and order as \code{y}, i.e. check using \dQuote{==} while handling \code{NA}s nicely. Default is \code{FALSE}.} \item{fmatch}{[\code{logical(1)}]\cr Use the set operations implemented in \code{\link[fastmatch]{fmatch}} in package \pkg{fastmatch}. If \pkg{fastmatch} is not installed, this silently falls back to \code{\link[base]{match}}. \code{\link[fastmatch]{fmatch}} modifies \code{y} by reference: A hash table is added as attribute which is used in subsequent calls.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertSubset}/\code{assert_subset} return \code{x} invisibly, whereas \code{checkSubset}/\code{check_subset} and \code{testSubset}/\code{test_subset} return \code{TRUE}. If the check is not successful, \code{assertSubset}/\code{assert_subset} throws an error message, \code{testSubset}/\code{test_subset} returns \code{FALSE}, and \code{checkSubset} returns a string with the error message. The function \code{expect_subset} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is equal to a given set } \note{ The object \code{x} must be of the same type as the set w.r.t. \code{\link[base]{typeof}}. Integers and doubles are both treated as numeric. } \examples{ testSetEqual(c("a", "b"), c("a", "b")) testSetEqual(1:3, 1:4) # x is not converted before the comparison (except for numerics) testSetEqual(factor("a"), "a") testSetEqual(1, "1") testSetEqual(1, as.integer(1)) } \seealso{ Other set: \code{\link{checkChoice}()}, \code{\link{checkDisjunct}()}, \code{\link{checkSubset}()} } \concept{set} checkmate/man/checkNull.Rd0000644000176200001440000000403413616076131015155 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkNull.R \name{checkNull} \alias{checkNull} \alias{check_null} \alias{assertNull} \alias{assert_null} \alias{testNull} \alias{test_null} \title{Check if an argument is NULL} \usage{ checkNull(x) check_null(x) assertNull(x, .var.name = vname(x), add = NULL) assert_null(x, .var.name = vname(x), add = NULL) testNull(x) test_null(x) } \arguments{ \item{x}{[any]\cr Object to check.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertNull}/\code{assert_null} return \code{x} invisibly, whereas \code{checkNull}/\code{check_null} and \code{testNull}/\code{test_null} return \code{TRUE}. If the check is not successful, \code{assertNull}/\code{assert_null} throws an error message, \code{testNull}/\code{test_null} returns \code{FALSE}, and \code{checkNull} returns a string with the error message. The function \code{expect_null} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is NULL } \examples{ testNull(NULL) testNull(1) } \seealso{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkAtomic}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkIntegerish}()}, \code{\link{checkInteger}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/assert.Rd0000644000176200001440000000250713616076131014551 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/assert.R \name{assert} \alias{assert} \title{Combine multiple checks into one assertion} \usage{ assert(..., combine = "or", .var.name = NULL) } \arguments{ \item{...}{[any]\cr List of calls to check functions.} \item{combine}{[\code{character(1)}]\cr \dQuote{or} or \dQuote{and} to combine the check functions with an OR or AND, respectively.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in error messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Throws an error if all checks fail and invisibly returns \code{TRUE} otherwise. } \description{ You can call this function with an arbitrary number of of \code{check*} functions, i.e. functions provided by this package or your own functions which return \code{TRUE} on success and the error message as \code{character(1)} otherwise. The resulting assertion is successful, if \code{combine} is \dQuote{or} (default) and at least one check evaluates to \code{TRUE} or \code{combine} is \dQuote{and} and all checks evaluate to \code{TRUE}. Otherwise, \code{assert} throws an informative error message. } \examples{ x = 1:10 assert(checkNull(x), checkInteger(x, any.missing = FALSE)) \dontrun{ x = 1 assert(checkChoice(x, c("a", "b")), checkDataFrame(x)) } } checkmate/man/wf.Rd0000644000176200001440000000140413616076131013657 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/checkFileExists.Rd0000644000176200001440000000673013616076131016327 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkFileExists.R \name{checkFileExists} \alias{checkFileExists} \alias{check_file_exists} \alias{assertFileExists} \alias{assert_file_exists} \alias{testFileExists} \alias{test_file_exists} \alias{expect_file_exists} \alias{checkFile} \alias{assertFile} \alias{assert_file} \alias{testFile} \alias{expect_file} \title{Check existence and access rights of files} \usage{ checkFileExists(x, access = "", extension = NULL) check_file_exists(x, access = "", extension = NULL) assertFileExists( x, access = "", extension = NULL, .var.name = vname(x), add = NULL ) assert_file_exists( x, access = "", extension = NULL, .var.name = vname(x), add = NULL ) testFileExists(x, access = "", extension = NULL) test_file_exists(x, access = "", extension = NULL) expect_file_exists( x, access = "", extension = NULL, info = NULL, label = vname(x) ) checkFile(x, access = "", extension = NULL) assertFile(x, access = "", extension = NULL, .var.name = vname(x), add = NULL) assert_file(x, access = "", extension = NULL, .var.name = vname(x), add = NULL) testFile(x, access = "", extension = NULL) expect_file(x, access = "", extension = NULL, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{access}{[\code{character(1)}]\cr Single string containing possible characters \sQuote{r}, \sQuote{w} and \sQuote{x} to force a check for read, write or execute access rights, respectively. Write and executable rights are not checked on Windows.} \item{extension}{[\code{character}]\cr Vector of allowed file extensions, matched case insensitive.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertFileExists}/\code{assert_file_exists} return \code{x} invisibly, whereas \code{checkFileExists}/\code{check_file_exists} and \code{testFileExists}/\code{test_file_exists} return \code{TRUE}. If the check is not successful, \code{assertFileExists}/\code{assert_file_exists} throws an error message, \code{testFileExists}/\code{test_file_exists} returns \code{FALSE}, and \code{checkFileExists} returns a string with the error message. The function \code{expect_file_exists} always returns an \code{\link[testthat]{expectation}}. } \description{ Check existence and access rights of files } \note{ The functions without the suffix \dQuote{exists} are deprecated and will be removed from the package in a future version due to name clashes. \code{test_file} has been unexported already. } \examples{ # Check if R's COPYING file is readable testFileExists(file.path(R.home(), "COPYING"), access = "r") # Check if R's COPYING file is readable and writable testFileExists(file.path(R.home(), "COPYING"), access = "rw") } \seealso{ Other filesystem: \code{\link{checkAccess}()}, \code{\link{checkDirectoryExists}()}, \code{\link{checkPathForOutput}()} } \concept{filesystem} checkmate/man/checkmate-package.Rd0000644000176200001440000000642013616076131016563 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}}} } } \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://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] } } checkmate/man/checkInt.Rd0000644000176200001440000000744613616076131015007 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}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertInt}/\code{assert_int} return \code{x} invisibly, whereas \code{checkInt}/\code{check_int} and \code{testInt}/\code{test_int} return \code{TRUE}. If the check is not successful, \code{assertInt}/\code{assert_int} throws an error message, \code{testInt}/\code{test_int} returns \code{FALSE}, and \code{checkInt} returns a string with the error message. The function \code{expect_int} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a single integerish value } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \note{ To perform an assertion and then convert to integer, use \code{\link{asInt}}. \code{assertInt} will not convert numerics to integer. } \examples{ testInt(1) testInt(-1, lower = 0) } \seealso{ Other scalars: \code{\link{checkCount}()}, \code{\link{checkFlag}()}, \code{\link{checkNumber}()}, \code{\link{checkScalarNA}()}, \code{\link{checkScalar}()}, \code{\link{checkString}()} } \concept{scalars} checkmate/man/checkTRUE.Rd0000644000176200001440000000311213616076131015016 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkTRUE.R \name{checkTRUE} \alias{checkTRUE} \alias{check_true} \alias{assertTRUE} \alias{assert_true} \alias{testTRUE} \alias{test_true} \title{Check if an argument is TRUE} \usage{ checkTRUE(x, na.ok = FALSE) check_true(x, na.ok = FALSE) assertTRUE(x, na.ok = FALSE, .var.name = vname(x), add = NULL) assert_true(x, na.ok = FALSE, .var.name = vname(x), add = NULL) testTRUE(x, na.ok = FALSE) test_true(x, na.ok = FALSE) } \arguments{ \item{x}{[any]\cr Object to check.} \item{na.ok}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{FALSE}.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertTRUE.}/\code{assert_true.} return \code{x} invisibly, whereas \code{checkTRUE.}/\code{check_true.} and \code{testTRUE.}/\code{test_true.} return \code{TRUE}. If the check is not successful, \code{assertTRUE.}/\code{assert_true.} throws an error message, \code{testTRUE.}/\code{test_true.} returns \code{FALSE}, and \code{checkTRUE.} returns a string with the error message. The function \code{expect_true.} always returns an \code{\link[testthat]{expectation}}. } \description{ Simply checks if an argument is \code{TRUE}. } \examples{ testTRUE(TRUE) testTRUE(FALSE) } checkmate/man/checkMatrix.Rd0000644000176200001440000001353513616076131015515 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).} \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}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertMatrix}/\code{assert_matrix} return \code{x} invisibly, whereas \code{checkMatrix}/\code{check_matrix} and \code{testMatrix}/\code{test_matrix} return \code{TRUE}. If the check is not successful, \code{assertMatrix}/\code{assert_matrix} throws an error message, \code{testMatrix}/\code{test_matrix} returns \code{FALSE}, and \code{checkMatrix} returns a string with the error message. The function \code{expect_matrix} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a matrix } \examples{ x = matrix(1:9, 3) colnames(x) = letters[1:3] testMatrix(x, nrows = 3, min.cols = 1, col.names = "named") } \seealso{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkAtomic}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkIntegerish}()}, \code{\link{checkInteger}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} Other compound: \code{\link{checkArray}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDataTable}()}, \code{\link{checkTibble}()} } \concept{basetypes} \concept{compound} checkmate/man/qassert.Rd0000644000176200001440000001111113616076131014721 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/qassert.R \name{qassert} \alias{qassert} \alias{qtest} \alias{qexpect} \title{Quick argument checks on (builtin) R types} \usage{ qassert(x, rules, .var.name = vname(x)) qtest(x, rules) qexpect(x, rules, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object the check.} \item{rules}{[\code{character}]\cr Set of rules. See details.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in error messages. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ \code{qassert} throws an \code{R} exception if object \code{x} does not comply to at least one of the \code{rules} and returns the tested object invisibly otherwise. \code{qtest} behaves the same way but returns \code{FALSE} if none of the \code{rules} comply. \code{qexpect} is intended to be inside the unit test framework \code{\link[testthat]{testthat}} and returns an \code{\link[testthat]{expectation}}. } \description{ The provided functions parse rules which allow to express some of the most frequent argument checks by typing just a few letters. } \details{ The rule is specified in up to three parts. \enumerate{ \item{ Class and missingness check. The first letter is an abbreviation for the class. If it is provided uppercase, missing values are prohibited. Supported abbreviations: \tabular{rl}{ \code{[bB]} \tab Bool / logical.\cr \code{[iI]} \tab Integer.\cr \code{[xX]} \tab Integerish (numeric convertible to integer, see \code{\link{checkIntegerish}}).\cr \code{[rR]} \tab Real / double.\cr \code{[cC]} \tab Complex.\cr \code{[nN]} \tab Numeric (integer or double).\cr \code{[sS]} \tab String / character.\cr \code{[fF]} \tab Factor\cr \code{[aA]} \tab Atomic.\cr \code{[vV]} \tab Atomic vector (see \code{\link{checkAtomicVector}}).\cr \code{[lL]} \tab List. Missingness is defined as \code{NULL} element.\cr \code{[mM]} \tab Matrix.\cr \code{[dD]} \tab Data.frame. Missingness is checked recursively on columns.\cr \code{[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/checkFactor.Rd0000644000176200001440000001403213616076131015460 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkFactor.R \name{checkFactor} \alias{checkFactor} \alias{check_factor} \alias{assertFactor} \alias{assert_factor} \alias{testFactor} \alias{test_factor} \alias{expect_factor} \title{Check if an argument is a factor} \usage{ checkFactor( x, levels = NULL, ordered = NA, empty.levels.ok = TRUE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, n.levels = NULL, min.levels = NULL, max.levels = NULL, unique = FALSE, names = NULL, null.ok = FALSE ) check_factor( x, levels = NULL, ordered = NA, empty.levels.ok = TRUE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, n.levels = NULL, min.levels = NULL, max.levels = NULL, unique = FALSE, names = NULL, null.ok = FALSE ) assertFactor( x, levels = NULL, ordered = NA, empty.levels.ok = TRUE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, n.levels = NULL, min.levels = NULL, max.levels = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_factor( x, levels = NULL, ordered = NA, empty.levels.ok = TRUE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, n.levels = NULL, min.levels = NULL, max.levels = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) testFactor( x, levels = NULL, ordered = NA, empty.levels.ok = TRUE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, n.levels = NULL, min.levels = NULL, max.levels = NULL, unique = FALSE, names = NULL, null.ok = FALSE ) test_factor( x, levels = NULL, ordered = NA, empty.levels.ok = TRUE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, n.levels = NULL, min.levels = NULL, max.levels = NULL, unique = FALSE, names = NULL, null.ok = FALSE ) expect_factor( x, levels = NULL, ordered = NA, empty.levels.ok = TRUE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, n.levels = NULL, min.levels = NULL, max.levels = NULL, unique = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{levels}{[\code{character}]\cr Vector of allowed factor levels.} \item{ordered}{[\code{logical(1)}]\cr Check for an ordered factor? If \code{FALSE} or \code{TRUE}, checks explicitly for an unordered or ordered factor, respectively. Default is \code{NA} which does not perform any additional check.} \item{empty.levels.ok}{[\code{logical(1)}]\cr Are empty levels allowed? Default is \code{TRUE}.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{n.levels}{[\code{integer(1)}]\cr Exact number of factor levels. Default is \code{NULL} (no check).} \item{min.levels}{[\code{integer(1)}]\cr Minimum number of factor levels. Default is \code{NULL} (no check).} \item{max.levels}{[\code{integer(1)}]\cr Maximum number of factor levels. Default is \code{NULL} (no check).} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertFactor}/\code{assert_factor} return \code{x} invisibly, whereas \code{checkFactor}/\code{check_factor} and \code{testFactor}/\code{test_factor} return \code{TRUE}. If the check is not successful, \code{assertFactor}/\code{assert_factor} throws an error message, \code{testFactor}/\code{test_factor} returns \code{FALSE}, and \code{checkFactor} returns a string with the error message. The function \code{expect_factor} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a factor } \examples{ x = factor("a", levels = c("a", "b")) testFactor(x) testFactor(x, empty.levels.ok = FALSE) } \seealso{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkAtomic}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkIntegerish}()}, \code{\link{checkInteger}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkCharacter.Rd0000644000176200001440000001424113616076131016140 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkCharacter.R \name{checkCharacter} \alias{checkCharacter} \alias{check_character} \alias{assertCharacter} \alias{assert_character} \alias{testCharacter} \alias{test_character} \alias{expect_character} \title{Check if an argument is a vector of type character} \usage{ checkCharacter( x, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE ) check_character( x, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE ) assertCharacter( x, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_character( x, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) testCharacter( x, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE ) test_character( x, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE ) expect_character( x, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{min.chars}{[\code{integer(1)}]\cr Minimum number of characters for each element of \code{x}.} \item{pattern}{[\code{character(1L)}]\cr Regular expression as used in \code{\link[base]{grepl}}. All non-missing elements of \code{x} must comply to this pattern.} \item{fixed}{[\code{character(1)}]\cr Substring to detect in \code{x}. Will be used as \code{pattern} in \code{\link[base]{grepl}} with option \code{fixed} set to \code{TRUE}. All non-missing elements of \code{x} must contain this substring.} \item{ignore.case}{[\code{logical(1)}]\cr See \code{\link[base]{grepl}}. Default is \code{FALSE}.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{sorted}{[\code{logical(1)}]\cr Elements must be sorted in ascending order. Missing values are ignored.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertCharacter}/\code{assert_character} return \code{x} invisibly, whereas \code{checkCharacter}/\code{check_character} and \code{testCharacter}/\code{test_character} return \code{TRUE}. If the check is not successful, \code{assertCharacter}/\code{assert_character} throws an error message, \code{testCharacter}/\code{test_character} returns \code{FALSE}, and \code{checkCharacter} returns a string with the error message. The function \code{expect_character} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a vector of type character } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testCharacter(letters, min.len = 1, any.missing = FALSE) testCharacter(letters, min.chars = 2) testCharacter("example", pattern = "xa") } \seealso{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkAtomic}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkIntegerish}()}, \code{\link{checkInteger}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkNames.Rd0000644000176200001440000001202113616076131015301 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{identical.to}.} \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}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertNamed}/\code{assert_named} return \code{x} invisibly, whereas \code{checkNamed}/\code{check_named} and \code{testNamed}/\code{test_named} return \code{TRUE}. If the check is not successful, \code{assertNamed}/\code{assert_named} throws an error message, \code{testNamed}/\code{test_named} returns \code{FALSE}, and \code{checkNamed} returns a string with the error message. The function \code{expect_named} always returns an \code{\link[testthat]{expectation}}. } \description{ Performs various checks on character vectors, usually names. } \examples{ x = 1:3 testNames(x, "unnamed") names(x) = letters[1:3] testNames(x, "unique") cn = c("Species", "Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width") assertNames(names(iris), permutation.of = cn) } \seealso{ Other attributes: \code{\link{checkClass}()}, \code{\link{checkMultiClass}()}, \code{\link{checkNamed}()} } \concept{attributes} checkmate/man/checkNumeric.Rd0000644000176200001440000001340613616076131015650 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkNumeric.R \name{checkNumeric} \alias{checkNumeric} \alias{check_numeric} \alias{assertNumeric} \alias{assert_numeric} \alias{testNumeric} \alias{test_numeric} \alias{expect_numeric} \title{Check that an argument is a vector of type numeric} \usage{ checkNumeric( x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE ) check_numeric( x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE ) assertNumeric( x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_numeric( x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) testNumeric( x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE ) test_numeric( x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE ) expect_numeric( x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{lower}{[\code{numeric(1)}]\cr Lower value all elements of \code{x} must be greater than 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 only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{sorted}{[\code{logical(1)}]\cr Elements must be sorted in ascending order. Missing values are ignored.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertNumeric}/\code{assert_numeric} return \code{x} invisibly, whereas \code{checkNumeric}/\code{check_numeric} and \code{testNumeric}/\code{test_numeric} return \code{TRUE}. If the check is not successful, \code{assertNumeric}/\code{assert_numeric} throws an error message, \code{testNumeric}/\code{test_numeric} returns \code{FALSE}, and \code{checkNumeric} returns a string with the error message. The function \code{expect_numeric} always returns an \code{\link[testthat]{expectation}}. } \description{ 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{checkAtomicVector}()}, \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{checkIntegerish}()}, \code{\link{checkInteger}()}, \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/checkPathForOutput.Rd0000644000176200001440000000603213616076131017027 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}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertPathForOutput}/\code{assert_path_for_output} return \code{x} invisibly, whereas \code{checkPathForOutput}/\code{check_path_for_output} and \code{testPathForOutput}/\code{test_path_for_output} return \code{TRUE}. If the check is not successful, \code{assertPathForOutput}/\code{assert_path_for_output} throws an error message, \code{testPathForOutput}/\code{test_path_for_output} returns \code{FALSE}, and \code{checkPathForOutput} returns a string with the error message. The function \code{expect_path_for_output} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if a file path can be 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/checkArray.Rd0000644000176200001440000001044713616076131015326 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkArray.R \name{checkArray} \alias{checkArray} \alias{check_array} \alias{assertArray} \alias{assert_array} \alias{testArray} \alias{test_array} \alias{expect_array} \title{Check if an argument is an array} \usage{ checkArray( x, mode = NULL, any.missing = TRUE, d = NULL, min.d = NULL, max.d = NULL, null.ok = FALSE ) check_array( x, mode = NULL, any.missing = TRUE, d = NULL, min.d = NULL, max.d = NULL, null.ok = FALSE ) assertArray( x, mode = NULL, any.missing = TRUE, d = NULL, min.d = NULL, max.d = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_array( x, mode = NULL, any.missing = TRUE, d = NULL, min.d = NULL, max.d = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) testArray( x, mode = NULL, any.missing = TRUE, d = NULL, min.d = NULL, max.d = NULL, null.ok = FALSE ) test_array( x, mode = NULL, any.missing = TRUE, d = NULL, min.d = NULL, max.d = NULL, null.ok = FALSE ) expect_array( x, mode = NULL, any.missing = TRUE, d = NULL, min.d = NULL, max.d = NULL, null.ok = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{mode}{[\code{character(1)}]\cr Storage mode of the array. Arrays can hold vectors, i.e. \dQuote{logical}, \dQuote{integer}, \dQuote{integerish}, \dQuote{double}, \dQuote{numeric}, \dQuote{complex}, \dQuote{character} and \dQuote{list}. You can also specify \dQuote{atomic} here to explicitly prohibit lists. Default is \code{NULL} (no check).} \item{any.missing}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{TRUE}.} \item{d}{[\code{integer(1)}]\cr Exact number of dimensions of array \code{x}. Default is \code{NULL} (no check).} \item{min.d}{[\code{integer(1)}]\cr Minimum number of dimensions of array \code{x}. Default is \code{NULL} (no check).} \item{max.d}{[\code{integer(1)}]\cr Maximum number of dimensions of array \code{x}. Default is \code{NULL} (no check).} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertArray}/\code{assert_array} return \code{x} invisibly, whereas \code{checkArray}/\code{check_array} and \code{testArray}/\code{test_array} return \code{TRUE}. If the check is not successful, \code{assertArray}/\code{assert_array} throws an error message, \code{testArray}/\code{test_array} returns \code{FALSE}, and \code{checkArray} returns a string with the error message. The function \code{expect_array} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is an array } \examples{ checkArray(array(1:27, dim = c(3, 3, 3)), d = 3) } \seealso{ Other basetypes: \code{\link{checkAtomicVector}()}, \code{\link{checkAtomic}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkIntegerish}()}, \code{\link{checkInteger}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} Other compound: \code{\link{checkDataFrame}()}, \code{\link{checkDataTable}()}, \code{\link{checkMatrix}()}, \code{\link{checkTibble}()} } \concept{basetypes} \concept{compound} checkmate/man/AssertCollection.Rd0000644000176200001440000000244113616076131016522 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/asInteger.Rd0000644000176200001440000000612613616076131015172 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 only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{sorted}{[\code{logical(1)}]\cr Elements must be sorted in ascending order. Missing values are ignored.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in error messages. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{na.ok}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{FALSE}.} \item{positive}{[\code{logical(1)}]\cr Must \code{x} be positive (>= 1)? Default is \code{FALSE}.} } \value{ Converted \code{x}. } \description{ \code{asInteger} is intended to be used for vectors while \code{asInt} is a specialization for scalar integers and \code{asCount} for scalar non-negative integers. Convertible are (a) atomic vectors with all elements \code{NA} and (b) double vectors with all elements being within \code{tol} range of an integer. 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/coalesce.Rd0000644000176200001440000000117613616076131015027 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/makeExpectation.Rd0000644000176200001440000000500613616076131016366 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/checkDouble.Rd0000644000176200001440000001303013616076131015451 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, 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, 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, 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, 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, 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, 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, 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 only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{sorted}{[\code{logical(1)}]\cr Elements must be sorted in ascending order. Missing values are ignored.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{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} returns 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{checkAtomicVector}()}, \code{\link{checkAtomic}()}, \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{checkIntegerish}()}, \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/vname.Rd0000644000176200001440000000073113616076131014353 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/checkFlag.Rd0000644000176200001440000000516013616076131015115 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkFlag.R \name{checkFlag} \alias{checkFlag} \alias{check_flag} \alias{assertFlag} \alias{assert_flag} \alias{testFlag} \alias{test_flag} \alias{expect_flag} \title{Check if an argument is a flag} \usage{ checkFlag(x, na.ok = FALSE, null.ok = FALSE) check_flag(x, na.ok = FALSE, null.ok = FALSE) assertFlag(x, na.ok = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_flag( x, na.ok = FALSE, null.ok = FALSE, .var.name = vname(x), add = NULL ) testFlag(x, na.ok = FALSE, null.ok = FALSE) test_flag(x, na.ok = FALSE, null.ok = FALSE) expect_flag(x, na.ok = FALSE, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{na.ok}{[\code{logical(1)}]\cr Are missing values allowed? Default is \code{FALSE}.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertFlag}/\code{assert_flag} return \code{x} invisibly, whereas \code{checkFlag}/\code{check_flag} and \code{testFlag}/\code{test_flag} return \code{TRUE}. If the check is not successful, \code{assertFlag}/\code{assert_flag} throws an error message, \code{testFlag}/\code{test_flag} returns \code{FALSE}, and \code{checkFlag} returns a string with the error message. The function \code{expect_flag} always returns an \code{\link[testthat]{expectation}}. } \description{ A flag is defined as single logical value. } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testFlag(TRUE) testFlag(1) } \seealso{ Other scalars: \code{\link{checkCount}()}, \code{\link{checkInt}()}, \code{\link{checkNumber}()}, \code{\link{checkScalarNA}()}, \code{\link{checkScalar}()}, \code{\link{checkString}()} } \concept{scalars} checkmate/man/checkClass.Rd0000644000176200001440000000617313616076131015316 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}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertClass}/\code{assert_class} return \code{x} invisibly, whereas \code{checkClass}/\code{check_class} and \code{testClass}/\code{test_class} return \code{TRUE}. If the check is not successful, \code{assertClass}/\code{assert_class} throws an error message, \code{testClass}/\code{test_class} returns \code{FALSE}, and \code{checkClass} returns a string with the error message. The function \code{expect_class} always returns an \code{\link[testthat]{expectation}}. } \description{ Check the class membership of an argument } \examples{ # Create an object with classes "foo" and "bar" x = 1 class(x) = c("foo", "bar") # is x of class "foo"? testClass(x, "foo") # is x of class "foo" and "bar"? testClass(x, c("foo", "bar")) # is x of class "foo" or "bar"? \dontrun{ assert( checkClass(x, "foo"), checkClass(x, "bar") ) } # is x most specialized as "bar"? testClass(x, "bar", ordered = TRUE) } \seealso{ 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/checkFunction.Rd0000644000176200001440000000724213616076131016034 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkFunction.R \name{checkFunction} \alias{checkFunction} \alias{check_function} \alias{assertFunction} \alias{assert_function} \alias{testFunction} \alias{test_function} \alias{expect_function} \title{Check if an argument is a function} \usage{ checkFunction(x, args = NULL, ordered = FALSE, nargs = NULL, null.ok = FALSE) check_function(x, args = NULL, ordered = FALSE, nargs = NULL, null.ok = FALSE) assertFunction( x, args = NULL, ordered = FALSE, nargs = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_function( x, args = NULL, ordered = FALSE, nargs = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) testFunction(x, args = NULL, ordered = FALSE, nargs = NULL, null.ok = FALSE) test_function(x, args = NULL, ordered = FALSE, nargs = NULL, null.ok = FALSE) expect_function( x, args = NULL, ordered = FALSE, nargs = NULL, null.ok = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{args}{[\code{character}]\cr Expected formal arguments. Checks that a function has no arguments if set to \code{character(0)}. Default is \code{NULL} (no check).} \item{ordered}{[\code{logical(1)}]\cr Flag whether the arguments provided in \code{args} must be the first \code{length(args)} arguments of the function in the specified order. Default is \code{FALSE}.} \item{nargs}{[\code{integer(1)}]\cr Required number of arguments, without \code{...}. Default is \code{NULL} (no check).} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertFunction}/\code{assert_function} return \code{x} invisibly, whereas \code{checkFunction}/\code{check_function} and \code{testFunction}/\code{test_function} return \code{TRUE}. If the check is not successful, \code{assertFunction}/\code{assert_function} throws an error message, \code{testFunction}/\code{test_function} returns \code{FALSE}, and \code{checkFunction} returns a string with the error message. The function \code{expect_function} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a function } \examples{ testFunction(mean) testFunction(mean, args = "x") } \seealso{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkAtomic}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkIntegerish}()}, \code{\link{checkInteger}()}, \code{\link{checkList}()}, \code{\link{checkLogical}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/checkChoice.Rd0000644000176200001440000000623113616076131015436 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkChoice.R \name{checkChoice} \alias{checkChoice} \alias{check_choice} \alias{assertChoice} \alias{assert_choice} \alias{testChoice} \alias{test_choice} \alias{expect_choice} \title{Check if an object is an element of a given set} \usage{ checkChoice(x, choices, null.ok = FALSE, fmatch = FALSE) check_choice(x, choices, null.ok = FALSE, fmatch = FALSE) assertChoice( x, choices, null.ok = FALSE, fmatch = FALSE, .var.name = vname(x), add = NULL ) assert_choice( x, choices, null.ok = FALSE, fmatch = FALSE, .var.name = vname(x), add = NULL ) testChoice(x, choices, null.ok = FALSE, fmatch = FALSE) test_choice(x, choices, null.ok = FALSE, fmatch = FALSE) expect_choice( x, choices, null.ok = FALSE, fmatch = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{choices}{[\code{atomic}]\cr Set of possible values.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{fmatch}{[\code{logical(1)}]\cr Use the set operations implemented in \code{\link[fastmatch]{fmatch}} in package \pkg{fastmatch}. If \pkg{fastmatch} is not installed, this silently falls back to \code{\link[base]{match}}. \code{\link[fastmatch]{fmatch}} modifies \code{y} by reference: A hash table is added as attribute which is used in subsequent calls.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertChoice}/\code{assert_choice} return \code{x} invisibly, whereas \code{checkChoice}/\code{check_choice} and \code{testChoice}/\code{test_choice} return \code{TRUE}. If the check is not successful, \code{assertChoice}/\code{assert_choice} throws an error message, \code{testChoice}/\code{test_choice} returns \code{FALSE}, and \code{checkChoice} returns a string with the error message. The function \code{expect_choice} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an object is an element of a given set } \note{ The object \code{x} must be of the same type as the set w.r.t. \code{\link[base]{typeof}}. Integers and doubles are both treated as numeric. } \examples{ testChoice("x", letters) # x is not converted before the comparison (except for numerics) testChoice(factor("a"), "a") testChoice(1, "1") testChoice(1, as.integer(1)) } \seealso{ Other set: \code{\link{checkDisjunct}()}, \code{\link{checkSetEqual}()}, \code{\link{checkSubset}()} } \concept{set} checkmate/man/checkScalarNA.Rd0000644000176200001440000000466413616076131015700 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkScalarNA.R \name{checkScalarNA} \alias{checkScalarNA} \alias{check_scalar_na} \alias{assertScalarNA} \alias{assert_scalar_na} \alias{testScalarNA} \alias{test_scalar_na} \alias{expect_scalar_na} \title{Check if an argument is a single missing value} \usage{ checkScalarNA(x, null.ok = FALSE) check_scalar_na(x, null.ok = FALSE) assertScalarNA(x, null.ok = FALSE, .var.name = vname(x), add = NULL) assert_scalar_na(x, null.ok = FALSE, .var.name = vname(x), add = NULL) testScalarNA(x, null.ok = FALSE) test_scalar_na(x, null.ok = FALSE) expect_scalar_na(x, null.ok = FALSE, info = NULL, label = vname(x)) } \arguments{ \item{x}{[any]\cr Object to check.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertScalarNA}/\code{assert_scalar_na} return \code{x} invisibly, whereas \code{checkScalarNA}/\code{check_scalar_na} and \code{testScalarNA}/\code{test_scalar_na} return \code{TRUE}. If the check is not successful, \code{assertScalarNA}/\code{assert_scalar_na} throws an error message, \code{testScalarNA}/\code{test_scalar_na} returns \code{FALSE}, and \code{checkScalarNA} returns a string with the error message. The function \code{expect_scalar_na} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a single missing value } \examples{ testScalarNA(1) testScalarNA(NA_real_) testScalarNA(rep(NA, 2)) } \seealso{ Other scalars: \code{\link{checkCount}()}, \code{\link{checkFlag}()}, \code{\link{checkInt}()}, \code{\link{checkNumber}()}, \code{\link{checkScalar}()}, \code{\link{checkString}()} } \concept{scalars} checkmate/man/checkDataTable.Rd0000644000176200001440000001413113616076131016063 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}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertDataTable}/\code{assert_data_table} return \code{x} invisibly, whereas \code{checkDataTable}/\code{check_data_table} and \code{testDataTable}/\code{test_data_table} return \code{TRUE}. If the check is not successful, \code{assertDataTable}/\code{assert_data_table} throws an error message, \code{testDataTable}/\code{test_data_table} returns \code{FALSE}, and \code{checkDataTable} returns a string with the error message. The function \code{expect_data_table} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a data table } \examples{ library(data.table) dt = as.data.table(iris) setkeyv(dt, "Species") setkeyv(dt, "Sepal.Length", physical = FALSE) testDataTable(dt) testDataTable(dt, key = "Species", index = "Sepal.Length", any.missing = FALSE) } \seealso{ Other compound: \code{\link{checkArray}()}, \code{\link{checkDataFrame}()}, \code{\link{checkMatrix}()}, \code{\link{checkTibble}()} } \concept{compound} checkmate/man/checkLogical.Rd0000644000176200001440000001124513616076131015617 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/checkLogical.R \name{checkLogical} \alias{checkLogical} \alias{check_logical} \alias{assertLogical} \alias{assert_logical} \alias{testLogical} \alias{test_logical} \alias{expect_logical} \title{Check if an argument is a vector of type logical} \usage{ checkLogical( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE ) check_logical( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE ) assertLogical( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) assert_logical( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, .var.name = vname(x), add = NULL ) testLogical( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE ) test_logical( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE ) expect_logical( x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE, info = NULL, label = vname(x) ) } \arguments{ \item{x}{[any]\cr Object to check.} \item{any.missing}{[\code{logical(1)}]\cr Are vectors with missing values allowed? Default is \code{TRUE}.} \item{all.missing}{[\code{logical(1)}]\cr Are vectors with only missing values allowed? Default is \code{TRUE}.} \item{len}{[\code{integer(1)}]\cr Exact expected length of \code{x}.} \item{min.len}{[\code{integer(1)}]\cr Minimal length of \code{x}.} \item{max.len}{[\code{integer(1)}]\cr Maximal length of \code{x}.} \item{unique}{[\code{logical(1)}]\cr Must all values be unique? Default is \code{FALSE}.} \item{names}{[\code{character(1)}]\cr Check for names. See \code{\link{checkNamed}} for possible values. Default is \dQuote{any} which performs no check at all. Note that you can use \code{\link{checkSubset}} to check for a specific set of names.} \item{null.ok}{[\code{logical(1)}]\cr If set to \code{TRUE}, \code{x} may also be \code{NULL}. In this case only a type check of \code{x} is performed, all additional checks are disabled.} \item{.var.name}{[\code{character(1)}]\cr Name of the checked object to print in assertions. Defaults to the heuristic implemented in \code{\link{vname}}.} \item{add}{[\code{AssertCollection}]\cr Collection to store assertion messages. See \code{\link{AssertCollection}}.} \item{info}{[character(1)]\cr Extra information to be included in the message for the testthat reporter. See \code{\link[testthat]{expect_that}}.} \item{label}{[\code{character(1)}]\cr Name of the checked object to print in messages. Defaults to the heuristic implemented in \code{\link{vname}}.} } \value{ Depending on the function prefix: If the check is successful, the functions \code{assertLogical}/\code{assert_logical} return \code{x} invisibly, whereas \code{checkLogical}/\code{check_logical} and \code{testLogical}/\code{test_logical} return \code{TRUE}. If the check is not successful, \code{assertLogical}/\code{assert_logical} throws an error message, \code{testLogical}/\code{test_logical} returns \code{FALSE}, and \code{checkLogical} returns a string with the error message. The function \code{expect_logical} always returns an \code{\link[testthat]{expectation}}. } \description{ Check if an argument is a vector of type logical } \details{ This function does not distinguish between \code{NA}, \code{NA_integer_}, \code{NA_real_}, \code{NA_complex_} \code{NA_character_} and \code{NaN}. } \examples{ testLogical(TRUE) testLogical(TRUE, min.len = 1) } \seealso{ Other basetypes: \code{\link{checkArray}()}, \code{\link{checkAtomicVector}()}, \code{\link{checkAtomic}()}, \code{\link{checkCharacter}()}, \code{\link{checkComplex}()}, \code{\link{checkDataFrame}()}, \code{\link{checkDate}()}, \code{\link{checkDouble}()}, \code{\link{checkEnvironment}()}, \code{\link{checkFactor}()}, \code{\link{checkFormula}()}, \code{\link{checkFunction}()}, \code{\link{checkIntegerish}()}, \code{\link{checkInteger}()}, \code{\link{checkList}()}, \code{\link{checkMatrix}()}, \code{\link{checkNull}()}, \code{\link{checkNumeric}()}, \code{\link{checkPOSIXct}()}, \code{\link{checkRaw}()}, \code{\link{checkVector}()} } \concept{basetypes} checkmate/man/anyInfinite.Rd0000644000176200001440000000105313616076131015520 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/DESCRIPTION0000644000176200001440000000463013616662435013723 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.0.0 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") ) URL: https://github.com/mllg/checkmate URLNote: https://github.com/mllg/checkmate BugReports: https://github.com/mllg/checkmate/issues NeedsCompilation: yes ByteCompile: yes Encoding: UTF-8 Depends: R (>= 3.0.0) Imports: backports (>= 1.1.0), utils Suggests: R6, fastmatch, data.table (>= 1.9.8), devtools, ggplot2, knitr, magrittr, microbenchmark, rmarkdown, testthat (>= 0.11.0), tinytest (>= 1.1.0), tibble License: BSD_3_clause + file LICENSE VignetteBuilder: knitr RoxygenNote: 7.0.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' '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: 2020-02-05 12:51:29 UTC; michel Author: Michel Lang [cre, aut] (), Bernd Bischl [ctb] Maintainer: Michel Lang Repository: CRAN Date/Publication: 2020-02-06 01:00:13 UTC checkmate/build/0000755000176200001440000000000013616535121013300 5ustar liggesuserscheckmate/build/vignette.rds0000644000176200001440000000033613616535121015641 0ustar liggesusersuM0 c< luᶁ!<98`_Ӿ}3!#lHp qawF/F,p/Ҽ- hp]e0Oq,D7% assert_numeric(lower = 0, upper = 1), x) expect_identical(iris %>% assert_data_frame(min.rows = 1) %>% ncol, 5L) }) checkmate/tests/testthat/test_anyNaN.R0000644000176200001440000000126313616076131017554 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_checkLogical.R0000644000176200001440000000112513616076131020735 0ustar liggesuserscontext("checkLogical") test_that("checkLogical", { myobj = TRUE expect_succ_all(Logical, myobj) myobj = 1 expect_fail_all(Logical, myobj) expect_true(testLogical(logical(0))) expect_false(testLogical(NULL)) expect_true(testLogical(TRUE)) expect_true(testLogical(NA)) expect_true(testLogical(NA_real_)) expect_true(testLogical(FALSE)) expect_false(testLogical(NA, any.missing=FALSE)) expect_false(testLogical(NA, all.missing=FALSE)) expect_false(testLogical(iris)) expect_true(testLogical(c(TRUE, FALSE), min.len = 2)) expect_error(assertLogical(1), "logical") }) checkmate/tests/testthat/test_checkDataFrame.R0000644000176200001440000001071013616076131021207 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_AssertCollection.R0000644000176200001440000000212613616076131021644 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_checkComplex.R0000644000176200001440000000121213616076131020767 0ustar liggesuserscontext("checkComplex") test_that("checkComplex", { myobj = 1+1i expect_succ_all(Complex, myobj) myobj = 1 expect_fail_all(Complex, myobj) expect_true(testComplex(complex(0L))) expect_false(testComplex(NULL)) expect_false(testComplex(TRUE)) expect_true(testComplex(NA)) expect_false(testComplex(NA, any.missing = FALSE)) expect_false(testComplex(NA, all.missing = FALSE)) expect_true(testComplex(NA_complex_)) expect_true(testComplex(1+1i)) expect_true(testComplex(as.complex(Inf))) expect_true(testComplex(c(1+1i, 2+1i), any.missing = FALSE, min.len = 1L, max.len = 3L)) expect_error(assertComplex(1), "complex") }) checkmate/tests/testthat/test_checkMultiClass.R0000644000176200001440000000063313616076131021446 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_checkTRUE.R0000644000176200001440000000026513616076131020146 0ustar liggesuserscontext("checkTRUE") test_that("checkTRUE", { expect_succ_all(TRUE, TRUE) expect_fail_all(TRUE, 1) expect_false(test_true(NA)) expect_true(test_true(NA, na.ok = TRUE)) }) checkmate/tests/testthat/test_checkNumber.R0000644000176200001440000000212613616076131020615 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.R0000644000176200001440000000073013616076131020235 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_matchArg.R0000644000176200001440000000121313616076131020111 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_checkDataTable.R0000644000176200001440000000451213616076131021207 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", { # 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_checkMatrix.R0000644000176200001440000000740013616076131020631 0ustar liggesuserscontext("checkMatrix") test_that("checkMatrix", { myobj = matrix(1:9, 3) expect_succ_all(Matrix, myobj) myobj = TRUE expect_fail_all(Matrix, myobj) x = matrix(1:9, 3) expect_true(testMatrix(x)) expect_true(testMatrix(matrix(nrow=0, ncol=0))) expect_false(testMatrix(NULL)) x[2,2] = NA expect_true(testMatrix(x)) expect_false(testMatrix(x, any.missing = FALSE)) xl = matrix(TRUE) xi = matrix(1L) xr = matrix(1.) xs = matrix("a") xc = matrix(1+1i) xx = array(list(1, 1), dim = c(1, 2)) xe = matrix(nrow = 0, ncol = 0); storage.mode(xe) = "double" expect_true(testMatrix(xl, "logical")) expect_true(testMatrix(xi, "integer")) expect_true(testMatrix(xr, "double")) expect_true(testMatrix(xe, "double")) expect_true(testMatrix(xr, "numeric")) expect_true(testMatrix(xc, "complex")) expect_true(testMatrix(xs, "character")) expect_true(testMatrix(xx, "list")) expect_false(testMatrix(xs, "logical")) expect_false(testMatrix(xs, "integer")) expect_false(testMatrix(xs, "double")) expect_false(testMatrix(xe, "logical")) expect_false(testMatrix(xs, "numeric")) expect_false(testMatrix(xs, "complex")) expect_false(testMatrix(xl, "character")) expect_false(testMatrix(xx, "numeric")) expect_false(testMatrix(xx, "atomic")) expect_true(testMatrix(xi, "integerish")) expect_true(testMatrix(xr, "integerish")) expect_false(testMatrix(xi+0.1, "integerish")) expect_true(testMatrix(x, min.rows = 1, min.cols = 1)) expect_true(testMatrix(x, 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))) }) checkmate/tests/testthat/test_anyInfinite.R0000644000176200001440000000141113616076131020640 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_checkInt.R0000644000176200001440000000225113616076131020116 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_checkFactor.R0000644000176200001440000000330513616076131020603 0ustar liggesuserscontext("checkFactor") test_that("checkFactor", { myobj = factor(letters[1:2]) expect_succ_all(Factor, myobj) myobj = letters[1:2] expect_fail_all(Factor, myobj) x = factor(c("a", "b"), levels = c("a", "b")) expect_true(testFactor(x)) expect_false(testFactor(integer(1))) expect_false(testFactor("a")) expect_true(testFactor(factor())) # expect_false(testFactor(integer(0))) expect_false(testFactor(NULL)) expect_true(testFactor(x, levels = rev(levels(x)))) expect_true(testFactor(x, empty.levels.ok = FALSE)) expect_true(testFactor(x, ordered = FALSE)) expect_false(testFactor(x, levels = c("a"))) expect_false(testFactor(x, levels = c("a", "b", "c"))) x = factor(c("a", "b"), levels = c("a", "b", "c"), ordered = TRUE) expect_true(testFactor(x, empty.levels.ok = TRUE)) expect_false(testFactor(x, empty.levels.ok = FALSE)) expect_true(testFactor(x, ordered = TRUE)) expect_false(testFactor(x, ordered = FALSE)) x = factor(c("a", "b"), levels = c("a", "b", "c")) expect_error(assertFactor(1), "factor") expect_error(assertFactor(x, levels = c("a")), "levels") expect_error(assertFactor(x, empty.levels.ok = FALSE), "empty") expect_error(assertFactor(x, ordered = TRUE), "ordered") x = as.ordered(x) expect_error(assertFactor(x, ordered = FALSE), "unordered") x = factor(c("a", "b")) expect_true(testFactor(x, n.levels = 2)) expect_true(testFactor(x, min.levels = 2)) expect_true(testFactor(x, max.levels = 2)) expect_false(testFactor(x, n.levels = 1)) expect_false(testFactor(x, min.levels = 3)) expect_false(testFactor(x, max.levels = 1)) expect_error(testFactor(x, n.levels = NA)) expect_error(assertFactor(x, n.levels = 1), "exactly 1 level") }) checkmate/tests/testthat/setup.R0000644000176200001440000000024013616076131016463 0ustar liggesusersif (getRversion() >= "3.6.0") { old_opts = options( warnPartialMatchArgs = TRUE, warnPartialMatchAttr = TRUE, warnPartialMatchDollar = TRUE ) } checkmate/tests/testthat/test_altreps.R0000644000176200001440000000206113616076131020037 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_checkList.R0000644000176200001440000000264213616076131020303 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_asType.R0000644000176200001440000000454113616076131017637 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_checkFunction.R0000644000176200001440000000347413616076131021161 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 }) checkmate/tests/testthat/test_checkScalar.R0000644000176200001440000000076113616076131020575 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_checkClass.R0000644000176200001440000000200713616076131020430 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_qassertr.R0000644000176200001440000000426113616076131020235 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_checkString.R0000644000176200001440000000227613616076131020641 0ustar liggesuserscontext("checkString") test_that("checkString", { expect_succ_all(String, "a") expect_succ_all(String, "") expect_fail_all(String, "", min.chars = 1) expect_fail_all(String, 1L) expect_succ_all(String, NA_character_, na.ok = TRUE, min.chars = 99) expect_succ_all(String, "xxxfooxxx", pattern = "foo") expect_succ_all(String, "xxxfooxxx", fixed = "foo") expect_fail_all(String, "xxxfooxxx", pattern = "bar") expect_fail_all(String, "xxxfooxxx", fixed = "bar") expect_succ_all(String, "xxxfooxxx", pattern = "FOO", ignore.case = TRUE) expect_fail_all(String, "xxxfooxxx", fixed = "FOO", ignore.case = FALSE) expect_false(testString(character(0))) expect_false(testString(NULL)) expect_true(testString("")) expect_true(testString("foo")) expect_true(testString(NA, na.ok = TRUE)) expect_false(testString(NA_character_)) expect_true(testString(NA_character_, na.ok = TRUE)) expect_true(testString(NA, na.ok = TRUE)) expect_true(testString("a", min.chars = 1)) expect_false(testString("", min.chars = 1)) expect_true(testString(NA_character_, min.chars = 1, na.ok = TRUE)) expect_true(testString(NA_real_, min.chars = 1, na.ok = TRUE)) expect_error(assertString(1)) }) checkmate/tests/testthat/test_checkNull.R0000644000176200001440000000037213616076131020300 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_checkPOSIXct.R0000644000176200001440000000403013616076131020612 0ustar liggesuserscontext("checkPOSIXct") test_that("checkPOSIXct", { origin = "1970-01-01" now = Sys.time() yesterday = now - 24 * 60 * 60 tomorrow = now + 24 * 60 * 60 now_est = as.POSIXct(as.numeric(now), tz = "EST", origin = origin) now_gmt = as.POSIXct(as.numeric(now), tz = "GMT", origin = origin) yesterday_gmt = as.POSIXct(as.numeric(now), tz = "GMT", origin = origin) tomorrow_gmt = as.POSIXct(as.numeric(now), tz = "GMT", origin = origin) expect_succ_all(POSIXct, now, lc = "posixct", cc = "POSIXct") expect_fail_all(POSIXct, 1, lc = "posixct", cc = "POSIXct") dates = c(yesterday, now, tomorrow, NA) expect_true(testPOSIXct(dates, min.len = 1, max.len = 10)) expect_true(testPOSIXct(dates, len = 4)) expect_true(testPOSIXct(dates, unique = TRUE)) expect_true(testPOSIXct(dates, all.missing = FALSE)) expect_true(testPOSIXct(dates, sorted = TRUE)) expect_true(testPOSIXct(c(now, now), sorted = TRUE)) expect_error(assertPOSIXct(c(dates, dates), unique = TRUE)) expect_error(assertPOSIXct(dates, any.missing = FALSE), "missing") expect_error(assertPOSIXct(rev(dates), sorted = TRUE), "sorted") expect_true(testPOSIXct(dates, lower = yesterday)) expect_true(checkPOSIXct(dates, upper = tomorrow)) expect_error(assertPOSIXct(dates, lower = now), ">=") expect_error(assertPOSIXct(dates, upper = now), "<=") x = checkPOSIXct(dates, lower = now) expect_true(grepl("[0-9]{4}-[0-9]{2}-[0-9]{2}", x)) x = checkPOSIXct(dates, upper = now) expect_true(grepl("[0-9]{4}-[0-9]{2}-[0-9]{2}", x)) # timezone checks expect_error(assertPOSIXct(now_est, lower = yesterday), "Timezones") expect_error(assertPOSIXct(now_est, upper = tomorrow), "Timezones") expect_error(assertPOSIXct(now, lower = yesterday_gmt), "Timezones") expect_error(assertPOSIXct(now, upper = tomorrow_gmt), "Timezones") expect_error(assertPOSIXct(now_est, lower = yesterday_gmt), "Timezones") expect_error(assertPOSIXct(now_est, upper = tomorrow_gmt), "Timezones") expect_true(testPOSIXct(now_gmt, lower = yesterday_gmt, upper = tomorrow_gmt)) }) checkmate/tests/testthat/test_checkIntegerish.R0000644000176200001440000000527413616076131021475 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") }) checkmate/tests/testthat/test_makeFunction.R0000644000176200001440000000446513616105435021022 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_checkCount.R0000644000176200001440000000147013616076131020456 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/teardown.R0000644000176200001440000000006613616076131017154 0ustar liggesusersif (getRversion() >= "3.6.0") { options(old_opts) } checkmate/tests/testthat/test_guessType.R0000644000176200001440000000262313616076131020361 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_checkInteger.R0000644000176200001440000000357413616076131020772 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") }) checkmate/tests/testthat/test_checkTibble.R0000644000176200001440000000107613616076131020571 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_checkFALSE.R0000644000176200001440000000027413616076131020221 0ustar liggesuserscontext("checkFALSE") test_that("checkFALSE", { expect_succ_all(FALSE, FALSE) expect_fail_all(FALSE, 1) expect_false(test_false(NA)) expect_true(test_false(NA, na.ok = TRUE)) }) checkmate/tests/testthat/test_checkCharacter.R0000644000176200001440000000452413616076131021265 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") }) checkmate/tests/testthat/test_checkArray.R0000644000176200001440000000275413616076131020452 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_anyMissing.R0000644000176200001440000000457513616076131020522 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_checkVector.R0000644000176200001440000000461213616076131020631 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_checkDate.R0000644000176200001440000000640513616076131020246 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_checkSetEqual.R0000644000176200001440000000362413616076131021114 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_messages.R0000644000176200001440000000132413616076131020175 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_checkDisjunct.R0000644000176200001440000000230113616076131021143 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_wf.R0000644000176200001440000000166213616076131017007 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/helper.R0000644000176200001440000000636313616076131016616 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_checkNumeric.R0000644000176200001440000000523513616076131020773 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)) } }) test_that("names check works", { expect_true(grepl("names", check_numeric(0:1, names = "unique"))) }) checkmate/tests/testthat/test_checkFormula.R0000644000176200001440000000050213616076131020766 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_include.R0000644000176200001440000000064613616076131020017 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_checkOS.R0000644000176200001440000000015513616076131017706 0ustar liggesuserscontext("checkOS") test_that("checkOS", { expect_succ_all(OS, c("linux", "mac", "windows", "solaris")) }) checkmate/tests/testthat/test_checkScalarNA.R0000644000176200001440000000057013616076131021012 0ustar liggesuserscontext("checkScalarNA") test_that("checkScalarNA", { expect_succ_all("ScalarNA", NA) expect_fail_all("ScalarNA", 1) expect_true(testScalarNA(NA_real_)) expect_false(testScalarNA(1)) expect_false(testScalarNA(rep(NA_character_, 2))) expect_expectation_successful(expect_scalar_na(NA), label = NULL) expect_error(assertScalarNA(integer(0)), "missing value") }) checkmate/tests/testthat/test_checkRaw.R0000644000176200001440000000103413616076131020113 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_qassert.R0000644000176200001440000002031213616076131020046 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"))) }) checkmate/tests/testthat/test_checkChoice.R0000644000176200001440000000307113616076131020557 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_checkSubset.R0000644000176200001440000000305413616076131020633 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_checkFilesystem.R0000644000176200001440000000547213616076131021520 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") }) checkmate/tests/testthat/test_checkAtomic.R0000644000176200001440000000256213616076131020605 0ustar liggesuserscontext("checkAtomic") li = list( list = list(1, 2), factor = factor("a"), integer = 1:2, NULL = NULL, data.frame = iris ) test_that("checkAtomic", { myobj = 1:2 expect_succ_all(Atomic, myobj) myobj = iris expect_fail_all(Atomic, myobj) expect_true(testAtomic(integer(0))) expect_true(testAtomic(NULL)) expect_true(testAtomic(1)) expect_true(testAtomic(integer(0))) expect_true(testAtomic(factor(1))) expect_true(testAtomic(NA, any.missing = TRUE)) expect_false(testAtomic(NA, any.missing = FALSE)) expect_false(testAtomic(NA, all.missing = FALSE)) expect_true(testAtomic(1, len=1)) expect_false(testAtomic(1, len=0)) expect_true(testAtomic(1, min.len=0)) expect_false(testAtomic(1, min.len=2)) expect_true(testAtomic(1, max.len=1)) expect_false(testAtomic(1, max.len=0)) expect_true(testAtomic(1, unique=TRUE)) expect_false(testAtomic(1, min.len=2)) expect_true(testAtomic(1, max.len=1)) expect_false(testAtomic(1, max.len=0)) expect_true(testAtomic(1, unique=TRUE)) expect_true(testAtomic(c(1,1), unique=FALSE)) expect_false(testAtomic(c(1,1), unique=TRUE)) expect_true(testAtomic(1, names="unnamed")) expect_true(testAtomic(setNames(1, "x"), names="named")) expect_false(testAtomic(1, names="unique")) expect_error(assertAtomic(iris), "atomic") expect_equal(vlapply(li, is.atomic), vlapply(li, testAtomic)) }) checkmate/tests/testthat/test_checkDouble.R0000644000176200001440000000472513616076131020606 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)) } }) checkmate/tests/testthat/test_checkAtomicVector.R0000644000176200001440000000337413616076131021772 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_checkEnvironment.R0000644000176200001440000000127113616076131021671 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/src/0000755000176200001440000000000013616535121012770 5ustar liggesuserscheckmate/src/guess_type.c0000644000176200001440000000201013616076131015315 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/find_min_nchar.h0000644000176200001440000000025413616076131016101 0ustar liggesusers#ifndef CHECKMATE_FIND_MIN_NCHAR_H_ #define CHECKMATE_FIND_MIN_NCHAR_H_ #include #include R_xlen_t find_min_nchar(SEXP, R_xlen_t, Rboolean); #endif checkmate/src/backports.h0000644000176200001440000000052613616076131015135 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/find_min_nchar.c0000644000176200001440000000107013616076131016071 0ustar liggesusers#include "find_min_nchar.h" R_xlen_t find_min_nchar(SEXP x, R_xlen_t n, Rboolean skip_na) { if (!isString(x)) { SEXP xs = PROTECT(coerceVector(x, STRSXP)); Rboolean res = find_min_nchar(xs, n, skip_na); UNPROTECT(1); return res; } const R_xlen_t nx = xlength(x); for (R_xlen_t i = 0; i < nx; i++) { if (STRING_ELT(x, i) == NA_STRING) { if (skip_na) continue; return i + 1; } if (xlength(STRING_ELT(x, i)) < n) { return i + 1; } } return 0; } checkmate/src/helper.h0000644000176200001440000000226513616076131014426 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 asNumber(SEXP, const char *); const char attribute_hidden * asString(SEXP, const char *); R_len_t attribute_hidden asCount(SEXP, const char *); R_xlen_t attribute_hidden asLength(SEXP, const char *); Rboolean attribute_hidden asFlag(SEXP, const char *); 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/src/integerish.c0000644000176200001440000000447013616076131015303 0ustar liggesusers#include #include #include "integerish.h" #include "backports.h" #include "all_missing.h" static inline int_err_t check_convertible_logical(SEXP x, Rboolean logicals_ok) { int_err_t res = { 0, (logicals_ok || all_missing_logical(x)) ? INT_OK : INT_TYPE }; return res; } static inline 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 int_err_t check_convertible_double(SEXP x, const double tol) { const double *xr = REAL_RO(x); const R_xlen_t n = length(x); 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 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 int_err_t check_convertible_complex(SEXP x, const double tol) { const Rcomplex * xc = COMPLEX_RO(x); const R_xlen_t n = length(x); int_err_t res = { 0, INT_OK }; for (R_xlen_t i = 0; i < n; i++) { int_check_t ok = is_unconvertible_complex(xc[i], tol); if (ok != INT_OK) { res.pos = i + 1; res.err = ok; break; } } return res; } int_err_t checkIntegerish(SEXP x, const double tol, Rboolean logicals_ok) { 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: 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) { 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/which_first.h0000644000176200001440000000032013616076131015446 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_infinite.c0000644000176200001440000000224513616076131015614 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/is_sorted.h0000644000176200001440000000024013616076131015131 0ustar liggesusers#ifndef CHECKMATE_IS_SORTED_H_ #define CHECKMATE_IS_SORTED_H_ #include #include #include Rboolean isSorted(SEXP x); #endif checkmate/src/init.c0000644000176200001440000001212213616076131014076 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); extern SEXP c_check_complex(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_count(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_dataframe(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_factor(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_flag(SEXP, SEXP, SEXP); extern SEXP c_check_int(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_integer(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_integerish(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_list(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_logical(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_matrix(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, 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); extern SEXP c_check_double(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_scalar(SEXP, SEXP, SEXP); extern SEXP c_check_string(SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_vector(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP c_check_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, 11}, {"c_check_complex", (DL_FUNC) &c_check_complex, 9}, {"c_check_count", (DL_FUNC) &c_check_count, 5}, {"c_check_dataframe", (DL_FUNC) &c_check_dataframe, 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, 12}, {"c_check_integerish", (DL_FUNC) &c_check_integerish, 13}, {"c_check_list", (DL_FUNC) &c_check_list, 9}, {"c_check_logical", (DL_FUNC) &c_check_logical, 9}, {"c_check_matrix", (DL_FUNC) &c_check_matrix, 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, 13}, {"c_check_double", (DL_FUNC) &c_check_double, 13}, {"c_check_scalar", (DL_FUNC) &c_check_scalar, 3}, {"c_check_string", (DL_FUNC) &c_check_string, 4}, {"c_check_vector", (DL_FUNC) &c_check_vector, 10}, {"c_check_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/any_missing.c0000644000176200001440000001025313616076131015456 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/all_missing.c0000644000176200001440000000640513616076131015443 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/any_nan.c0000644000176200001440000000203013616076131014553 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/qassert.c0000644000176200001440000004543613616076131014633 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 } 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 } cmp_t; static const char * CMPSTR[] = { "<", "<=", "==", ">=", ">", "!=" }; typedef R_xlen_t(*miss_fun_t)(SEXP); typedef Rboolean(*dd_cmp)(double, double); typedef Rboolean(*ll_cmp)(R_xlen_t, R_xlen_t); typedef struct { dd_cmp fun; double cmp; cmp_t op; } bound_t; typedef struct { struct { Rboolean(*fun)(SEXP); class_t name; } class; miss_fun_t missing_fun; struct { ll_cmp fun; R_xlen_t cmp; cmp_t op; } len; bound_t lower; bound_t upper; } checker_t; typedef struct { Rboolean ok; char msg[255]; } msg_t; static inline Rboolean ii_eq(const R_xlen_t x, const R_xlen_t y) { return x == y; } static inline Rboolean ii_lt(const R_xlen_t x, const R_xlen_t y) { return x < y; } static inline Rboolean ii_gt(const R_xlen_t x, const R_xlen_t y) { return x > y; } static inline Rboolean ii_le(const R_xlen_t x, const R_xlen_t y) { return x <= y; } static inline Rboolean ii_ge(const R_xlen_t x, const R_xlen_t y) { return x >= y; } static inline Rboolean dd_lt(const double x, const double y) { return x < y; } static inline Rboolean dd_gt(const double x, const double y) { return x > y; } static inline Rboolean dd_le(const double x, const double y) { return x <= y; } static inline Rboolean dd_ge(const double x, const double y) { return x >= y; } static inline Rboolean dd_ne(const double x, const double y) { return x != y; } static msg_t MSGT = { .ok = TRUE }; static msg_t MSGF = { .ok = FALSE }; static msg_t message(const char *fmt, ...) { msg_t msg = { .ok = FALSE }; va_list vargs; va_start(vargs, fmt); vsnprintf(msg.msg, 255, fmt, vargs); va_end(vargs); return msg; } /*********************************************************************************************************************/ /* Some helper functions */ /*********************************************************************************************************************/ static msg_t check_bound(SEXP x, const bound_t bound) { if (isReal(x)) { const double *xp = REAL_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(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_double; 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(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(checker_t *checker, const char *rule) { switch(rule[0]) { case '\0': checker->lower.fun = NULL; checker->upper.fun = NULL; return 0; case '(': checker->lower.fun = &dd_gt; checker->lower.op = GT; break; case '[': checker->lower.fun = &dd_ge; checker->lower.op = GE; break; default: error("Invalid bound definition, missing opening '(' or '[': %s", rule); } char *end; const char *start = rule + 1; double cmp = strtod(start, &end); if (start == end) { if (checker->lower.op == GT) { checker->lower.fun = &dd_ne; checker->lower.cmp = R_NegInf; checker->lower.op = NE; } else { checker->lower.fun = NULL; } } else { checker->lower.cmp = cmp; } switch(*end) { case ',' : start = end + 1; case ')' : case ']' : break; default : error("Invalid bound definition, error parsing lower bound, missing separator ',' or missing closing ')' or ']': %s", rule); } cmp = strtod(start, &end); if (*end == ')') { if (start == end) { checker->upper.fun = &dd_ne; checker->upper.cmp = R_PosInf; checker->upper.op = NE; } else { checker->upper.fun = &dd_lt; checker->upper.cmp = cmp; checker->upper.op = LT; } } else if (*end == ']') { if (start == end) { checker->upper.fun = NULL; } else { checker->upper.fun = &dd_le; checker->upper.cmp = cmp; checker->upper.op = LE; } } else { error("Invalid bound definition, error parsing upper bound or missing closing ')' or ']': %s", rule); } return end - rule + 1; } static void parse_rule(checker_t *checker, const char *rule) { const R_len_t nchars = strlen(rule); if (nchars == 0) error("Empty rule"); rule += parse_class(checker, rule); rule += parse_length(checker, rule); rule += parse_bounds(checker, rule); if (rule[0] == '\0') return; error("Additional chars found in rule!"); } /*********************************************************************************************************************/ /* Second step: check SEXP using a checker_t object */ /*********************************************************************************************************************/ static msg_t check_rule(SEXP x, const checker_t *checker, 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) { msg_t msg = check_bound(x, checker->lower); if (!msg.ok) return msg; } if (checker->upper.fun != NULL) { msg_t msg = check_bound(x, checker->upper); if (!msg.ok) return msg; } return MSGT; } /*********************************************************************************************************************/ /* qassert stuff */ /*********************************************************************************************************************/ static inline R_len_t qassert1(SEXP x, const checker_t *checker, msg_t *result, const R_len_t nrules) { for (R_len_t i = 0; i < nrules; i++) { result[i] = check_rule(x, &checker[i], result[i].ok); if (result[i].ok) return 0; } return 1; } static inline R_len_t qassert_list(SEXP x, const checker_t *checker, msg_t *result, const R_len_t nrules) { if (!isNewList(x) || isNull(x)) error("Argument 'x' must be a list or data.frame"); const R_len_t nx = xlength(x); for (R_xlen_t i = 0; i < nx; i++) { if (qassert1(VECTOR_ELT(x, i), checker, result, nrules) != 0) return i + 1; } return 0; } /* exported for other packages */ SEXP qassert(SEXP x, const char *rule, const char *name) { checker_t checker; parse_rule(&checker, rule); msg_t result = check_rule(x, &checker, TRUE); if (!result.ok) error("Variable '%s': %s", name, result.msg); return x; } SEXP attribute_hidden c_qassert(SEXP x, SEXP rules, SEXP recursive) { const 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); msg_t result[nrules]; checker_t checker[nrules]; SEXP tmp; for (R_len_t i = 0; i < nrules; i++) { tmp = STRING_ELT(rules, i); if (tmp == NA_STRING) error("Rule may not be NA"); parse_rule(&checker[i], CHAR(tmp)); result[i].ok = TRUE; } if (LOGICAL_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 checker_t *checker, const R_len_t nrules) { msg_t result; for (R_len_t i = 0; i < nrules; i++) { result = check_rule(x, &checker[i], FALSE); if (result.ok) return TRUE; } return FALSE; } static inline Rboolean qtest_list(SEXP x, const checker_t *checker, const R_len_t nrules, R_len_t depth) { if (!isNewList(x) || isNull(x)) error("Argument 'x' must be a list or data.frame"); const R_len_t nx = xlength(x); if (depth > 1) { for (R_xlen_t i = 0; i < nx; i++) { if (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) { checker_t checker; parse_rule(&checker, rule); return qtest1(x, &checker, 1); } SEXP attribute_hidden c_qtest(SEXP x, SEXP rules, SEXP recursive, SEXP depth) { const R_len_t nrules = length(rules); if (!isString(rules)) error("Argument 'rules' must be a string"); if (nrules == 0) return ScalarLogical(TRUE); checker_t checker[nrules]; SEXP tmp; for (R_len_t i = 0; i < nrules; i++) { tmp = STRING_ELT(rules, i); if (tmp == NA_STRING) error("Rule may not be NA"); parse_rule(&checker[i], CHAR(STRING_ELT(rules, i))); } if (LOGICAL_RO(recursive)[0]) return ScalarLogical(qtest_list(x, checker, nrules, asCount(depth, "depth"))); return ScalarLogical(qtest1(x, checker, nrules)); } checkmate/src/any_nan.h0000644000176200001440000000031013616076131014557 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/is_sorted.c0000644000176200001440000000405713616076131015136 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 && xr[i] == NA_REAL) i++; for (R_xlen_t j = i + 1; j < n; j++) { if (xr[j] != NA_REAL) { if (xr[i] > xr[j]) return FALSE; i = j; } } return TRUE; } static Rboolean 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 isSorted(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/integerish.h0000644000176200001440000000075013616076131015305 0ustar liggesusers#ifndef CHECKMATE_INTEGERISH_H_ #define CHECKMATE_INTEGERISH_H_ #include #include #include #define INTEGERISH_DEFAULT_TOL sqrt(DOUBLE_EPS) typedef enum { INT_OK, INT_TYPE, INT_RANGE, INT_TOL, INT_COMPLEX } int_check_t; typedef struct { R_xlen_t pos; int_check_t err; } int_err_t; Rboolean isIntegerish(SEXP, double, Rboolean); SEXP attribute_hidden c_is_integerish(SEXP, SEXP); int_err_t checkIntegerish(SEXP, const double, Rboolean); #endif checkmate/src/guess_type.h0000644000176200001440000000033013616076131015325 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/qassert.h0000644000176200001440000000050713616076131014626 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/any_missing.h0000644000176200001440000000147213616076131015466 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/Makevars0000644000176200001440000000003613616076131014464 0ustar liggesusersPKG_CFLAGS=${_R_DEBUG_FLAGS_} checkmate/src/helper.c0000644000176200001440000001221613616076131014416 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 asNumber(SEXP x, const char *vname) { if (!isNumeric(x)) error("Argument '%s' must be a number, but is %s", vname, guess_type(x)); if (xlength(x) != 1) error("Argument '%s' must have length 1, but has length %i", vname, xlength(x)); double xd = asReal(x); if (ISNAN(xd)) error("Argument '%s' may not be missing", vname); return xd; } const char attribute_hidden * asString(SEXP x, const char *vname) { if (!isString(x) || xlength(x) != 1) error("Argument '%s' must be a string, but is %s", vname, guess_type(x)); if (find_missing_string(x) > 0) error("Argument '%s' may not be missing", vname); return CHAR(STRING_ELT(x, 0)); } R_len_t attribute_hidden asCount(SEXP x, const char *vname) { if (length(x) != 1) error("Argument '%x' must have length 1", vname); if (!isIntegerish(x, INTEGERISH_DEFAULT_TOL, FALSE)) error("Argument '%s' must be numeric and close to an integer", vname); int xi = asInteger(x); if (xi == NA_INTEGER) error("Argument '%s' may not be missing", vname); if (xi < 0) error("Argument '%s' must be >= 0", vname); return xi; } R_xlen_t attribute_hidden asLength(SEXP x, const char *vname) { if (length(x) != 1) error("Argument '%x' must have length 1", vname); switch(TYPEOF(x)) { case INTSXP:; int xi = INTEGER_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 (xr == NA_REAL) error("Argument '%s' may not be missing", vname); if (xr < 0) error("Argument '%s' must be >= 0", vname); if (fabs(xr - nearbyint(xr)) >= INTEGERISH_DEFAULT_TOL) error("Argument '%s' is not close to an integer", vname); return (R_xlen_t) xr; } error("Argument '%s' must be a length, but is %s", vname, guess_type(x)); } Rboolean attribute_hidden asFlag(SEXP x, const char *vname) { if (!isLogical(x) || xlength(x) != 1) error("Argument '%s' must be a flag, but is %s", vname, guess_type(x)); Rboolean xb = LOGICAL_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 isReal(x) && inherits(x, "POSIXct"); } Rboolean is_class_raw(SEXP x) { return TYPEOF(x) == RAWSXP; } checkmate/src/all_missing.h0000644000176200001440000000114313616076131015442 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/which_first.c0000644000176200001440000000272213616076131015451 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/checks.c0000644000176200001440000007264713616076131014415 0ustar liggesusers#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_min_nchar.h" #include "helper.h" #include "guess_type.h" static char msg[255] = ""; #define HANDLE_TYPE(expr, expected) \ if (!(expr)) { \ snprintf(msg, 255, "Must be of type '%s', not '%s'", expected, guess_type(x)); \ return ScalarString(mkChar(msg)); \ } #define HANDLE_TYPE_NULL(expr, expected, null_ok) \ if (isNull((x))) { \ if (asFlag((null_ok), "null.ok")) \ return ScalarLogical(TRUE); \ snprintf(msg, 255, "Must be of type '%s', not 'NULL'", expected); \ return ScalarString(mkChar(msg)); \ } else { \ if (!(expr)) { \ snprintf(msg, 255, "Must be of type '%s'%s, not '%s'", expected, asFlag(null_ok, "null_ok") ? " (or 'NULL')" : "", guess_type(x)); \ return ScalarString(mkChar(msg)); \ } \ } #define HANDLE_INTEGERISH_NULL(tol, null_ok) \ if (isNull((x))) { \ if (asFlag((null_ok), "null.ok")) \ return ScalarLogical(TRUE); \ snprintf(msg, 255, "Must be of type 'integerish', not 'NULL'"); \ return ScalarString(mkChar(msg)); \ } else { \ int_err_t ok = checkIntegerish(x, dtol, FALSE); \ switch(ok.err) { \ case INT_OK: break; \ case INT_TYPE: snprintf(msg, 255, "Must be of type 'integerish'%s, not '%s'", asFlag(null_ok, "null_ok") ? " (or 'NULL')" : "", guess_type(x)); return ScalarString(mkChar(msg)); \ case INT_RANGE: snprintf(msg, 255, "Must be of type 'integerish', but element %ld is not in integer range", ok.pos); return ScalarString(mkChar(msg)); \ case INT_TOL: snprintf(msg, 255, "Must be of type 'integerish', but element %ld is not close to an integer", ok.pos); return ScalarString(mkChar(msg)); \ case INT_COMPLEX: snprintf(msg, 255, "Must be of type 'integerish', but element %ld has an imaginary part", ok.pos); return ScalarString(mkChar(msg)); \ } \ } #define HANDLE_NA(x, na_ok) \ if (is_scalar_na((x))) { \ if (asFlag((na_ok), "na.ok")) \ return ScalarLogical(TRUE); \ return result("May not be NA"); \ }; #define ASSERT_TRUE(x) if (!(x)) return ScalarString(mkChar(msg)); #define ASSERT_TRUE_UNPROTECT(x, p) \ Rboolean TMP = (x); \ UNPROTECT((p)); \ if (!TMP) return ScalarString(mkChar(msg)); /*********************************************************************************************************************/ /* Some helpers */ /*********************************************************************************************************************/ static Rboolean message(const char *fmt, ...) { va_list vargs; va_start(vargs, fmt); vsnprintf(msg, 255, fmt, vargs); va_end(vargs); return FALSE; } static SEXP result(const char *fmt, ...) { va_list vargs; va_start(vargs, fmt); vsnprintf(msg, 255, fmt, vargs); va_end(vargs); return ScalarString(mkChar(msg)); } static 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 = asNumber(lower, "lower"); if (R_FINITE(tmp)) { const R_xlen_t n = length(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 = asNumber(upper, "upper"); if (R_FINITE(tmp)) { const R_xlen_t n = length(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"))); const Rboolean null_tz = isNull(tz); 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"))); if (null_tz != isNull(lower_tz) || (!null_tz && !isNull(lower_tz) && strcmp(CHAR(STRING_ELT(tz, 0)), CHAR(STRING_ELT(lower_tz, 0))) != 0)) { UNPROTECT(2); return message("Timezones of 'x' and 'lower' must match"); } const double tmp = REAL_RO(lower)[0]; const double *xp = REAL_RO(x); 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(2); return message("Element %i is not >= %s", i + 1, fmt); } } UNPROTECT(1); } 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"))); if (null_tz != isNull(upper_tz) || (!null_tz && !isNull(upper_tz) && strcmp(CHAR(STRING_ELT(tz, 0)), CHAR(STRING_ELT(upper_tz, 0))) != 0)) { UNPROTECT(2); return message("Timezones of 'x' and 'upper' must match"); } const double tmp = REAL_RO(upper)[0]; const double *xp = REAL_RO(x); 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(2); return message("Element %i is not <= %s", i + 1, fmt); } } UNPROTECT(1); } UNPROTECT(1); 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, FALSE); 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 = asLength(len, "len"); if (xlength(x) != n) return message("Must have length %g, but has length %g", (double)n, (double)xlength(x)); } if (!isNull(min_len)) { R_xlen_t n = asLength(min_len, "min.len"); if (xlength(x) < n) return message("Must have length >= %g, but has length %g", (double)n, (double)xlength(x)); } if (!isNull(max_len)) { R_xlen_t n = asLength(max_len, "max.len"); if (xlength(x) > n) return message("Must have length <= %g, but has length %g", (double)n, (double)xlength(x)); } return TRUE; } static Rboolean check_vector_missings(SEXP x, SEXP any_missing, SEXP all_missing) { if (!asFlag(any_missing, "any.missing")) { R_xlen_t pos = find_missing_vector(x); if (pos > 0) return message("Contains missing values (element %i)", pos); } if (!asFlag(all_missing, "all.missing") && all_missing_atomic(x)) return message("Contains only missing values"); return TRUE; } static Rboolean check_vector_unique(SEXP x, SEXP unique) { if (asFlag(unique, "unique")) { 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, asString(names, "names"), "names"); return TRUE; } static Rboolean check_vector_finite(SEXP x, SEXP finite) { // FIXME: pos if (asFlag(finite, "finite") && any_infinite(x)) return message("Must be finite"); return TRUE; } static Rboolean check_matrix_dims(SEXP x, SEXP min_rows, SEXP 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 = asLength(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 = asLength(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 = asLength(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 = asLength(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 = asLength(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 = asCount(cols, "cols"); if (xcols != cmp) return message("Must have exactly %i cols, but has %i cols", cmp, xcols); } } return TRUE; } static Rboolean check_storage(SEXP x, SEXP mode) { if (!isNull(mode)) { const char * const storage = asString(mode, "mode"); if (strcmp(storage, "logical") == 0) { if (!isLogical(x)) return message("Must store logicals"); } else if (strcmp(storage, "integer") == 0) { if (!isInteger(x)) return message("Must store integers"); } else if (strcmp(storage, "double") == 0) { if (!isReal(x)) return message("Must store doubles"); } else if (strcmp(storage, "integerish") == 0) { if (!isIntegerish(x, INTEGERISH_DEFAULT_TOL, FALSE)) return message("Must store integerish values"); } else if (strcmp(storage, "numeric") == 0) { if (!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 (asFlag(sorted, "sorted") && xlength(x) > 1) { if (!isSorted(x)) return message("Must be sorted"); } return TRUE; } /*********************************************************************************************************************/ /* Exported check functions */ /*********************************************************************************************************************/ SEXP attribute_hidden c_check_character(SEXP x, SEXP min_chars, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP sorted, SEXP names, SEXP null_ok) { HANDLE_TYPE_NULL(is_class_string(x) || all_missing_atomic(x), "character", null_ok); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); if (!isNull(min_chars)) { R_xlen_t n = asCount(min_chars, "min.chars"); if (n > 0 && find_min_nchar(x, n, TRUE) > 0) return result("All elements must have at least %i characters", n); } 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 null_ok) { HANDLE_TYPE_NULL(is_class_complex(x) || all_missing_atomic(x), "complex", null_ok); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_vector_unique(x, unique)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_dataframe(SEXP x, SEXP any_missing, SEXP all_missing, SEXP min_rows, SEXP 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, asString(row_names, "row.names"), "rownames"), nprotect); } if (!isNull(col_names)) { ASSERT_TRUE(check_named(x, asString(col_names, "col.names"), "colnames")); } if (!asFlag(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 (!asFlag(all_missing, "all.missing") && all_missing_frame(x)) { return result("Contains only missing values"); } return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_factor(SEXP x, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP names, SEXP null_ok) { HANDLE_TYPE_NULL(is_class_factor(x) || all_missing_atomic(x), "factor", null_ok); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_vector_unique(x, unique)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_integer(SEXP x, SEXP lower, SEXP upper, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP sorted, SEXP names, SEXP null_ok) { HANDLE_TYPE_NULL(is_class_integer(x) || all_missing_atomic(x), "integer", null_ok); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_bounds(x, lower, upper)); ASSERT_TRUE(check_vector_unique(x, unique)); ASSERT_TRUE(check_vector_sorted(x, sorted)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_integerish(SEXP x, SEXP tol, SEXP lower, SEXP upper, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP sorted, SEXP names, SEXP null_ok) { double dtol = asNumber(tol, "tol"); HANDLE_INTEGERISH_NULL(dtol, null_ok); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_bounds(x, lower, upper)); ASSERT_TRUE(check_vector_unique(x, unique)); ASSERT_TRUE(check_vector_sorted(x, sorted)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_list(SEXP x, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP names, SEXP null_ok) { HANDLE_TYPE_NULL(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_logical(SEXP x, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP names, SEXP null_ok) { HANDLE_TYPE_NULL(is_class_logical(x) || all_missing_atomic(x), "logical", null_ok); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_vector_unique(x, unique)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_matrix(SEXP x, SEXP mode, SEXP any_missing, SEXP all_missing, SEXP min_rows, SEXP 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, asString(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, asString(col_names, "col.names"), "colnames"), 1); } if (!asFlag(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 (!asFlag(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 (!asFlag(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 = asCount(d, "d"); if (ndim != di) return result("Must be a %i-d array, but has dimension %i", di, ndim); } if (!isNull(min_d)) { R_len_t di = asCount(min_d, "min.d"); if (ndim < di) return result("Must have >=%i dimensions, but has dimension %i", di, ndim); } if (!isNull(max_d)) { R_len_t di = asCount(max_d, "max.d"); if (ndim > di) return result("Must have <=%i dimensions, but has dimension %i", di, ndim); } return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_named(SEXP x, SEXP type) { if (!isNull(type) && xlength(x) > 0) ASSERT_TRUE(check_named(x, asString(type, "type"), "Object")); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_names(SEXP x, SEXP type, SEXP what) { if (!(isString(x) || isNull(x))) return result("Must be a character vector"); ASSERT_TRUE(check_names(x, asString(type, "type"), asString(what, "what"))); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_numeric(SEXP x, SEXP lower, SEXP upper, SEXP finite, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP sorted, SEXP names, SEXP null_ok) { HANDLE_TYPE_NULL(is_class_numeric(x) || all_missing_atomic(x), "numeric", null_ok); ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_bounds(x, lower, upper)); ASSERT_TRUE(check_vector_finite(x, finite)); ASSERT_TRUE(check_vector_unique(x, unique)); ASSERT_TRUE(check_vector_sorted(x, sorted)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_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 null_ok) { HANDLE_TYPE_NULL(is_class_double(x) || all_missing_atomic(x), "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_vector(SEXP x, SEXP strict, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP names, SEXP null_ok) { HANDLE_TYPE_NULL(isVector(x), "vector", null_ok); if (asFlag(strict, "strict")) { SEXP attr = ATTRIB(x); HANDLE_TYPE( (length(attr) == 0 || (TAG(attr) == R_NamesSymbol)) && CDR(attr) == R_NilValue, "vector"); } ASSERT_TRUE(check_vector_len(x, len, min_len, max_len)); ASSERT_TRUE(check_vector_names(x, names)); ASSERT_TRUE(check_vector_missings(x, any_missing, all_missing)); ASSERT_TRUE(check_vector_unique(x, unique)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_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 = asNumber(tol, "tol"); HANDLE_TYPE_NULL(isIntegerish(x, dtol, FALSE), "count", null_ok); if (xlength(x) != 1) return result("Must have length 1"); const int pos = (int) asFlag(positive, "positive"); if (asInteger(x) < pos) return result("Must be >= %i", pos); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_int(SEXP x, SEXP na_ok, SEXP lower, SEXP upper, SEXP tol, SEXP null_ok) { double dtol = asNumber(tol, "tol"); HANDLE_NA(x, na_ok); HANDLE_TYPE_NULL(isIntegerish(x, dtol, FALSE), "single integerish value", null_ok); if (xlength(x) != 1) return result("Must have length 1"); ASSERT_TRUE(check_bounds(x, lower, upper)); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_number(SEXP x, SEXP na_ok, SEXP lower, SEXP upper, SEXP finite, SEXP null_ok) { HANDLE_NA(x, na_ok); HANDLE_TYPE_NULL(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 min_chars, SEXP null_ok) { HANDLE_NA(x, na_ok); HANDLE_TYPE_NULL(isString(x), "string", null_ok); if (xlength(x) != 1) return result("Must have length 1"); if (!isNull(min_chars)) { R_xlen_t n = asCount(min_chars, "min.chars"); if (find_min_nchar(x, n, TRUE) > 0) return result("Must have at least %i characters", n); } return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_scalar(SEXP x, SEXP na_ok, SEXP null_ok) { HANDLE_NA(x, na_ok); HANDLE_TYPE_NULL(isVectorAtomic(x), "atomic scalar", null_ok); if (xlength(x) != 1) return result("Must have length 1"); return ScalarLogical(TRUE); } SEXP attribute_hidden c_check_posixct(SEXP x, SEXP lower, SEXP upper, SEXP any_missing, SEXP all_missing, SEXP len, SEXP min_len, SEXP max_len, SEXP unique, SEXP sorted, SEXP null_ok) { HANDLE_TYPE_NULL(is_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/any_infinite.h0000644000176200001440000000033413616076131015616 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/checks.h0000644000176200001440000000376013616076131014410 0ustar liggesusers#ifndef CHECKMATE_CHECKS_H_ #define CHECKMATE_CHECKS_H_ #include #include #include SEXP attribute_hidden c_check_array(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_atomic(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_atomic_vector(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_character(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_complex(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_dataframe(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_factor(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_integer(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_integerish(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_list(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_logical(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_matrix(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_named(SEXP, SEXP); SEXP attribute_hidden c_check_names(SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_numeric(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_vector(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_count(SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_flag(SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_int(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_number(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_scalar(SEXP, SEXP, SEXP); SEXP attribute_hidden c_check_string(SEXP, SEXP, SEXP, SEXP); #endif checkmate/vignettes/0000755000176200001440000000000013616535121014211 5ustar liggesuserscheckmate/vignettes/tinytest.Rmd0000644000176200001440000000217613616076131016547 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} 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.Rmd0000644000176200001440000003107513616076131016610 0ustar liggesusers--- title: "Checkmate" author: "Michel Lang" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{checkmate} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r,include=FALSE} library(checkmate) ``` Ever used an R function that produced a not-very-helpful error message, just to discover after minutes of debugging that you simply passed a wrong argument? Blaming the laziness of the package author for not doing such standard checks (in a dynamically typed language such as R) is at least partially unfair, as R makes theses types of checks cumbersome and annoying. Well, that's how it was in the past. Enter checkmate. Virtually **every standard type of user error** when passing arguments into function can be caught with a simple, readable line which produces an **informative error message** in case. A substantial part of the package was written in C to **minimize any worries about execution time overhead**. ## Intro As a motivational example, consider you have a function to calculate the faculty of a natural number and the user may choose between using either the stirling approximation or R's `factorial` function (which internally uses the gamma function). Thus, you have two arguments, `n` and `method`. Argument `n` must obviously be a positive natural number and `method` must be either `"stirling"` or `"factorial"`. Here is a version of all the hoops you need to jump through to ensure that these simple requirements are met: ```{r} fact <- function(n, method = "stirling") { if (length(n) != 1) stop("Argument 'n' must have length 1") if (!is.numeric(n)) stop("Argument 'n' must be numeric") if (is.na(n)) stop("Argument 'n' may not be NA") if (is.double(n)) { if (is.nan(n)) stop("Argument 'n' may not be NaN") if (is.infinite(n)) stop("Argument 'n' must be finite") if (abs(n - round(n, 0)) > sqrt(.Machine$double.eps)) stop("Argument 'n' must be an integerish value") n <- as.integer(n) } if (n < 0) stop("Argument 'n' must be >= 0") if (length(method) != 1) stop("Argument 'method' must have length 1") if (!is.character(method) || !method %in% c("stirling", "factorial")) stop("Argument 'method' must be either 'stirling' or 'factorial'") if (method == "factorial") factorial(n) else sqrt(2 * pi * n) * (n / exp(1))^n } ``` And for comparison, here is the same function using checkmate: ```{r} fact <- function(n, method = "stirling") { assertCount(n) assertChoice(method, c("stirling", "factorial")) if (method == "factorial") factorial(n) else sqrt(2 * pi * n) * (n / exp(1))^n } ``` ## Function overview The functions can be split into four functional groups, indicated by their prefix. If prefixed with `assert`, an error is thrown if the corresponding check fails. Otherwise, the checked object is returned invisibly. There are many different coding styles out there in the wild, but most R programmers stick to either `camelBack` or `underscore_case`. Therefore, `checkmate` offers all functions in both flavors: `assert_count` is just an alias for `assertCount` but allows you to retain your favorite style. The family of functions prefixed with `test` always return the check result as logical value. Again, you can use `test_count` and `testCount` interchangeably. Functions starting with `check` return the error message as a string (or `TRUE` otherwise) and can be used if you need more control and, e.g., want to grep on the returned error message. `expect` is the last family of functions and is intended to be used with the [testthat package](https://cran.r-project.org/package=testthat). All performed checks are logged into the `testthat` reporter. Because `testthat` uses the `underscore_case`, the extension functions only come in the underscore style. All functions are categorized into objects to check on the [package help page](https://mllg.github.io/checkmate/reference/checkmate-package). ## In case you miss flexibility You can use [assert](https://mllg.github.io/checkmate/reference/assert) to perform multiple checks at once and throw an assertion if all checks fail. Here is an example where we check that x is either of class `foo` or class `bar`: ```{r} f <- function(x) { assert( checkClass(x, "foo"), checkClass(x, "bar") ) } ``` Note that `assert(, combine = "or")` and `assert(, combine = "and")` allow to control the logical combination of the specified checks, and that the former is the default. ## Argument Checks for the Lazy The following functions allow a special syntax to define argument checks using a special format specification. E.g., `qassert(x, "I+")` asserts that `x` is an integer vector with at least one element and no missing values. This very simple domain specific language covers a large variety of frequent argument checks with only a few keystrokes. You choose what you like best. * [qassert](https://mllg.github.io/checkmate/reference/qassert) * [qassertr](https://mllg.github.io/checkmate/reference/qassertr) ## checkmate as testthat extension To extend [testthat](https://cran.r-project.org/package=testthat), you need to IMPORT, DEPEND or SUGGEST on the `checkmate` package. Here is a minimal example: ```{r,eval=FALSE} # file: tests/test-all.R library(testthat) library(checkmate) # for testthat extensions test_check("mypkg") ``` Now you are all set and can use more than 30 new expectations in your tests. ```{r,eval=FALSE} test_that("checkmate is a sweet extension for testthat", { x = runif(100) expect_numeric(x, len = 100, any.missing = FALSE, lower = 0, upper = 1) # or, equivalent, using the lazy style: qexpect(x, "N100[0,1]") }) ``` ## Speed considerations In comparison with tediously writing the checks yourself in R (c.f. factorial example at the beginning of the vignette), R is sometimes a tad faster while performing checks on scalars. This seems odd at first, because checkmate is mostly written in C and should be comparably fast. Yet many of the functions in the `base` package are not regular functions, but primitives. While primitives jump directly into the C code, checkmate has to use the considerably slower `.Call` interface. As a result, it is possible to write (very simple) checks using only the base functions which, under some circumstances, slightly outperform checkmate. However, if you go one step further and wrap the custom check into a function to convenient re-use it, the performance gain is often lost (see benchmark 1). For larger objects the tide has turned because checkmate avoids many unnecessary intermediate variables. Also note that the quick/lazy implementation in `qassert`/`qtest`/`qexpect` is often a tad faster because only two arguments have to be evaluated (the object and the rule) to determine the set of checks to perform. Below you find some (probably unrepresentative) benchmark. But also note that this one here has been executed from inside `knitr` which is often the cause for outliers in the measured execution time. Better run the benchmark yourself to get unbiased results. ### Benchmark 1: Assert that `x` is a flag ```{r,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](http://r-pkgs.had.co.nz/src.html#clang) section in Hadley's Book "R Packages" or [WRE](https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Registering-native-routines). Here is a step-by-step guide to get you started: 1. Add `checkmate` to your "Imports" and "LinkingTo" sections in your DESCRIPTION file. 2. Create a stub C source file `"checkmate_stub.c"`, see 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/R/0000755000176200001440000000000013616077256012414 5ustar liggesuserscheckmate/R/checkDate.R0000644000176200001440000000457013616076131014407 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/anyNaN.R0000644000176200001440000000072113616076131013712 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/checkScalar.R0000644000176200001440000000207513616076131014735 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/checkFlag.R0000644000176200001440000000207113616076131014375 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/vname.R0000644000176200001440000000073513616076131013641 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/checkR6.R0000644000176200001440000000533613616076131014022 0ustar liggesusers#' Check if an argument is a R6 class #' #' @templateVar fn Class #' @template x #' @inheritParams checkClass #' @param cloneable [\code{logical(1)}]\cr #' If \code{TRUE}, check that \code{x} has a \code{clone} method. If \code{FALSE}, ensure that #' \code{x} is not cloneable. #' @param public [\code{character}]\cr #' Names of expected public slots. This includes active bindings. #' @param private [\code{character}]\cr #' Names of expected private slots. #' @template null.ok #' @template checker #' @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/checkAccess.R0000644000176200001440000000402013616076131014721 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/zzz.R0000644000176200001440000001007513616077256013377 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}}} #' } #' #' @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 "_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/checkDisjunct.R0000644000176200001440000000273413616076131015315 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) { if (length(x) == 0L || length(y) == 0) return(TRUE) qassert(y, "a") if (isTRUE(fmatch) && requireNamespace("fastmatch", quietly = TRUE)) match = fastmatch::fmatch i = (match(x, y, 0L) > 0L) if (any(i)) return(sprintf("Must be disjunct from set %s, but has %s", set_collapse(y), set_collapse(x[i]))) return(TRUE) } #' @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/qassert.R0000644000176200001440000001202513616076131014210 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/allMissing.R0000644000176200001440000000054013616076131014627 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/checkAtomic.R0000644000176200001440000000245013616076131014741 0ustar liggesusers#' Check that an argument is an atomic vector #' #' @description #' For the definition of \dQuote{atomic}, see \code{\link[base]{is.atomic}}. #' #' @templateVar fn Atomic #' @template x #' @inheritParams checkVector #' @template checker #' @useDynLib checkmate c_check_atomic #' @export #' @family basetypes #' @family atomicvector #' @examples #' testAtomic(letters, min.len = 1L, any.missing = FALSE) checkAtomic = function(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL) { .Call(c_check_atomic, x, any.missing, all.missing, len, min.len, max.len, unique, names) } #' @export #' @rdname checkAtomic check_atomic = checkAtomic #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkAtomic assertAtomic = makeAssertionFunction(checkAtomic, c.fun = "c_check_atomic", 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/assert.R0000644000176200001440000000436313616076131014035 0ustar liggesusers#' Combine multiple checks into one assertion #' #' @description #' You can call this function with an arbitrary number of of \code{check*} #' functions, i.e. functions provided by this package or your own functions which #' return \code{TRUE} on success and the error message as \code{character(1)} otherwise. #' The resulting assertion is successful, if \code{combine} is #' \dQuote{or} (default) and at least one check evaluates to \code{TRUE} or #' \code{combine} is \dQuote{and} and all checks evaluate to \code{TRUE}. #' Otherwise, \code{assert} throws an informative error message. #' #' @param ... [any]\cr #' List of calls to check functions. #' @param combine [\code{character(1)}]\cr #' \dQuote{or} or \dQuote{and} to combine the check functions with an OR #' or AND, respectively. #' @template var.name #' @return Throws an error if all checks fail and invisibly returns #' \code{TRUE} otherwise. #' @export #' @examples #' x = 1:10 #' assert(checkNull(x), checkInteger(x, any.missing = FALSE)) #' \dontrun{ #' x = 1 #' assert(checkChoice(x, c("a", "b")), checkDataFrame(x)) #' } assert = function(..., combine = "or", .var.name = NULL) { assertChoice(combine, c("or", "and")) dots = match.call(expand.dots = FALSE)$... env = parent.frame() if (combine == "or") { msgs = character(length(dots)) for (i in seq_along(dots)) { val = eval(dots[[i]], envir = env) if (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") mstop("Assertion failed. %s", msgs) } else { mstop("Assertion on '%s' failed. %s.", .var.name, msgs) } } else { for (i in seq_along(dots)) { val = eval(dots[[i]], envir = env) if (!isTRUE(val)) { if (is.null(.var.name)) .var.name = as.character(dots[[1L]])[2L] mstop("Assertion on '%s' failed. %s.", .var.name, val) } } } invisible(TRUE) } checkmate/R/checkNumeric.R0000644000176200001440000000345413616076131015134 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 null.ok #' @template checker #' @family basetypes #' @useDynLib checkmate c_check_numeric #' @export #' @examples #' testNumeric(1) #' testNumeric(1, min.len = 1, lower = 0) checkNumeric = function(x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) { .Call(c_check_numeric, x, lower, upper, finite, any.missing, all.missing, len, min.len, max.len, unique, sorted, names, null.ok) } #' @export #' @rdname checkNumeric check_numeric = checkNumeric #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkNumeric assertNumeric = makeAssertionFunction(checkNumeric, c.fun = "c_check_numeric", 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/makeExpectation.R0000644000176200001440000001122113616076131015644 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'") info = if (is.null(info)) res else sprintf("%s\nAdditional info: %s", res, info) testthat::expect_true(res, info = info, label = sprintf("Check on %s", label)) invisible(x) } 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/checkFactor.R0000644000176200001440000000702213616076131014743 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/checkPathForOutput.R0000644000176200001440000000452613616076131016317 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/checkCount.R0000644000176200001440000000254613616076131014623 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/isIntegerish.R0000644000176200001440000000021113616076131015155 0ustar liggesusers#' @useDynLib checkmate c_is_integerish isIntegerish = function(x, tol = sqrt(.Machine$double.eps)) { .Call(c_is_integerish, x, tol) } checkmate/R/checkDataFrame.R0000644000176200001440000000310713616076131015351 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/checkDataTable.R0000644000176200001440000000527513616076131015356 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/checkChoice.R0000644000176200001440000000356513616076131014727 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/checkEnvironment.R0000644000176200001440000000321513616076131016031 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/R/checkIntegerish.R0000644000176200001440000000360113616076131015625 0ustar liggesusers#' @title Check if an object is an integerish vector #' #' @description #' An integerish value is defined as value safely convertible to integer. #' This includes integers and numeric values which are close to an integer #' w.r.t. a numeric tolerance. #' #' @note #' To convert from integerish to integer, use \code{\link{asInteger}}. #' #' @templateVar fn Integerish #' @template x #' @template na-handling #' @inheritParams checkInteger #' @inheritParams checkVector #' @template sorted #' @template tol #' @template coerce #' @template null.ok #' @template checker #' @family basetypes #' @useDynLib checkmate c_check_integerish #' @export #' @examples #' testIntegerish(1L) #' testIntegerish(1.) #' testIntegerish(1:2, lower = 1L, upper = 2L, any.missing = FALSE) checkIntegerish = function(x, tol = sqrt(.Machine$double.eps), lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) { .Call(c_check_integerish, x, tol, lower, upper, any.missing, all.missing, len, min.len, max.len, unique, sorted, names, null.ok) } #' @export #' @rdname checkIntegerish check_integerish = checkIntegerish #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkIntegerish assertIntegerish = makeAssertionFunction(checkIntegerish, c.fun = "c_check_integerish", 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/checkFileExists.R0000644000176200001440000000476613616076131015620 0ustar liggesusers#' Check existence and access rights of files #' #' @note #' The functions without the suffix \dQuote{exists} are deprecated and will be removed #' from the package in a future version due to name clashes. #' \code{test_file} has been unexported already. #' #' @templateVar fn FileExists #' @template x #' @inheritParams checkAccess #' @param extension [\code{character}]\cr #' Vector of allowed file extensions, matched case insensitive. #' @template checker #' @family filesystem #' @export #' @examples #' # Check if R's COPYING file is readable #' testFileExists(file.path(R.home(), "COPYING"), access = "r") #' #' # Check if R's COPYING file is readable and writable #' testFileExists(file.path(R.home(), "COPYING"), access = "rw") checkFileExists = function(x, access = "", extension = NULL) { if (!qtest(x, "S+")) return("No file provided") w = wf(dir.exists(x)) if (length(w) > 0L) return(sprintf("File expected, but directory in place: '%s'", x[w])) w = wf(!file.exists(x)) if (length(w) > 0L) return(sprintf("File does not exist: '%s'", x[w])) checkAccess(x, access) %and% checkFileExtension(x, extension) } checkFileExtension = function(x, extension = NULL) { if (!is.null(extension)) { qassert(extension, "S+") pos = regexpr("\\.([[:alnum:]]+)$", x) ext = ifelse(pos > -1L, tolower(substring(x, pos + 1L)), "") if (any(ext %nin% tolower(extension))) return(sprintf("File extension must be in {'%s'}", paste0(extension, collapse = "','"))) } return(TRUE) } #' @export #' @rdname checkFileExists check_file_exists = checkFileExists #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkFileExists assertFileExists = makeAssertionFunction(checkFileExists, 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/checkMatrix.R0000644000176200001440000000500113616076131014764 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/checkDouble.R0000644000176200001440000000276513616076131014750 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 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, null.ok = FALSE) { .Call(c_check_double, x, lower, upper, finite, any.missing, all.missing, len, min.len, max.len, unique, sorted, names, 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/makeAssertion.R0000644000176200001440000000735013616076131015340 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)) { 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)) storage.mode(x) = \"integer\"; invisible(x)") } formals(new.fun) = fun.args body(new.fun) = parse(text = paste("{", body, "}")) environment(new.fun) = env return(new.fun) } checkmate/R/checkOS.R0000644000176200001440000000230313616076131014043 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/checkScalarNA.R0000644000176200001440000000231613616076131015152 0ustar liggesusers#' Check if an argument is a single missing value #' #' @templateVar fn ScalarNA #' @template x #' @template null.ok #' @template checker #' @family scalars #' @export #' @examples #' testScalarNA(1) #' testScalarNA(NA_real_) #' testScalarNA(rep(NA, 2)) checkScalarNA = function(x, null.ok = FALSE) { qassert(null.ok, "B1") if (is.null(x)) { if (null.ok) return(TRUE) return("Must be a scalar missing value, not 'NULL'") } if (length(x) != 1L || !is.na(x)) return(paste0("Must be a scalar missing value", if (null.ok) " (or 'NULL')" else "")) return(TRUE) } #' @export #' @rdname checkScalarNA check_scalar_na = checkScalarNA #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkScalarNA assertScalarNA = makeAssertionFunction(checkScalarNA, 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/checkList.R0000644000176200001440000000611613616076131014443 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]{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/checkComplex.R0000644000176200001440000000240413616076131015133 0ustar liggesusers#' Check if an argument is a vector of type complex #' #' @templateVar fn Complex #' @template x #' @template na-handling #' @inheritParams checkVector #' @template null.ok #' @template checker #' @family basetypes #' @useDynLib checkmate c_check_complex #' @export #' @examples #' testComplex(1) #' testComplex(1+1i) checkComplex = function(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) { .Call(c_check_complex, x, any.missing, all.missing, len, min.len, max.len, unique, names, null.ok) } #' @export #' @rdname checkComplex check_complex = checkComplex #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkComplex assertComplex = makeAssertionFunction(checkComplex, c.fun = "c_check_complex", 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/checkAtomicVector.R0000644000176200001440000000510613616076131016125 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/anyInfinite.R0000644000176200001440000000100313616076131014775 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/anyMissing.R0000644000176200001440000000212713616076131014651 0ustar liggesusers#' Check if an object contains missing values #' #' @description #' Supported are atomic types (see \code{\link[base]{is.atomic}}), lists and data frames. #' Missingness is defined as \code{NA} or \code{NaN} for atomic types and data frame columns, #' \code{NULL} is defined as missing for lists.\cr #' \code{allMissing} applied to a \code{data.frame} returns \code{TRUE} if at least one column has #' only non-missing values. If you want to perform the less frequent check that there is not a single #' non-missing observation present in the \code{data.frame}, use \code{all(sapply(df, allMissing))} #' instead. #' #' @param x [\code{ANY}]\cr #' Object to check. #' @return [\code{logical(1)}] Returns \code{TRUE} if any (\code{anyMissing}) or all (\code{allMissing}) #' elements of \code{x} are missing (see details), \code{FALSE} otherwise. #' @useDynLib checkmate c_any_missing #' @export #' @examples #' anyMissing(c(1, 1)) #' anyMissing(c(1, NA)) #' anyMissing(list(1, NULL)) #' #' x = iris #' x[, "Species"] = NA #' anyMissing(x) #' allMissing(x) anyMissing = function(x) { .Call(c_any_missing, x) } checkmate/R/checkPOSIXct.R0000644000176200001440000000326613616076131014764 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/checkTRUE.R0000644000176200001440000000146713616076131014313 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.R0000644000176200001440000000271513616076131015126 0ustar liggesusers#' Check if an argument is vector of type integer #' #' @templateVar fn Integer #' @template x #' @template na-handling #' @inheritParams checkVector #' @template bounds #' @template sorted #' @template null.ok #' @template checker #' @family basetypes #' @seealso \code{\link{asInteger}} #' @useDynLib checkmate c_check_integer #' @export #' @examples #' testInteger(1L) #' testInteger(1.) #' testInteger(1:2, lower = 1, upper = 2, any.missing = FALSE) checkInteger = function(x, lower = -Inf, upper = Inf, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) { .Call(c_check_integer, x, lower, upper, any.missing, all.missing, len, min.len, max.len, unique, sorted, names, null.ok) } #' @export #' @rdname checkInteger check_integer = checkInteger #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkInteger assertInteger = makeAssertionFunction(checkInteger, c.fun = "c_check_integer", 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/asInteger.R0000644000176200001440000000404213616076131014447 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/qassertr.R0000644000176200001440000000454413616076131014401 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/checkNull.R0000644000176200001440000000156613616076131014446 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.R0000644000176200001440000000332613616076131014554 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/checkTibble.R0000644000176200001440000000330713616076131014730 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/checkFunction.R0000644000176200001440000000510513616076131015312 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(0L) if (length(args) == 0L) { if (length(fargs) > 0L) return("May not have any arguments") return(TRUE) } qassert(ordered, "B1") if (ordered) { if (any(args != head(fargs, length(args)))) { return(sprintf("Must have first formal arguments (ordered): %s", paste0(args, collapse = ","))) } } else { tmp = setdiff(args, fargs) if (length(tmp)) return(sprintf("Must have formal arguments: %s", paste0(tmp, collapse = ","))) } } if (!is.null(nargs)) { nargs = asCount(nargs) fnargs = length(setdiff(names(formals(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/makeTest.R0000644000176200001440000000353013616076131014304 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/checkFALSE.R0000644000176200001440000000151613616076131014361 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/checkDirectoryExists.R0000644000176200001440000000413313616076131016671 0ustar liggesusers#' Check for existence and access rights of directories #' #' @note #' The functions without the suffix \dQuote{exists} are deprecated and will be removed #' from the package in a future version due to name clashes. #' #' @templateVar fn DirectoryExists #' @template x #' @inheritParams checkAccess #' @inheritParams checkFile #' @template checker #' @family filesystem #' @export #' @examples #' # Is R's home directory readable? #' testDirectory(R.home(), "r") #' #' # Is R's home directory readable and writable? #' testDirectory(R.home(), "rw") checkDirectoryExists = function(x, access = "") { if (!qtest(x, "S+")) return("No directory provided") w = wf(!file.exists(x)) if (length(w) > 0L) return(sprintf("Directory '%s' does not exists", x[w])) w = wf(!dir.exists(x)) if (length(w) > 0L) return(sprintf("Directory expected, but file in place: '%s'", x[w])) checkAccess(x, access) } #' @export #' @rdname checkDirectoryExists check_directory_exists = checkDirectoryExists #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkDirectoryExists assertDirectoryExists = makeAssertionFunction(checkDirectoryExists, 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/checkString.R0000644000176200001440000000233613616076131014776 0ustar liggesusers#' Check if an argument is a string #' #' @description #' A string is defined as a scalar character vector. #' #' @templateVar fn String #' @template x #' @template na-handling #' @template na.ok #' @inheritParams checkCharacter #' @template null.ok #' @template checker #' @family scalars #' @export #' @useDynLib checkmate c_check_string #' @examples #' testString("a") #' testString(letters) checkString = function(x, na.ok = FALSE, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, null.ok = FALSE) { .Call(c_check_string, x, na.ok, min.chars, null.ok) %and% checkCharacterPattern(x, pattern, fixed, ignore.case) } #' @export #' @rdname checkString check_string = checkString #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkString assertString = makeAssertionFunction(checkString, 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/helper.R0000644000176200001440000000141613616076131014007 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 = "','")) } set_collapse = function(x) { if (length(x) == 0L) return("{}") sprintf("{'%s'}", paste0(unique(x), collapse = "','")) } checkmate/R/AssertCollection.R0000644000176200001440000000375313616076131016013 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/checkNames.R0000644000176200001440000001066013616076131014572 0ustar liggesusers#' Check names to comply to specific rules #' #' @description #' Performs various checks on character vectors, usually names. #' #' @templateVar fn Named #' @param x [\code{character} || \code{NULL}]\cr #' Names to check using rules defined via \code{type}. #' @param type [character(1)]\cr #' Type of formal check(s) to perform on the names. #' \describe{ #' \item{unnamed:}{Checks \code{x} to be \code{NULL}.} #' \item{named:}{Checks \code{x} for regular names which excludes names to be \code{NA} or empty (\code{""}).} #' \item{unique:}{Performs checks like with \dQuote{named} and additionally tests for non-duplicated names.} #' \item{strict:}{Performs checks like with \dQuote{unique} and additionally fails for names with UTF-8 characters and names which do not comply to R's variable name restrictions. As regular expression, this is \dQuote{^[.]*[a-zA-Z]+[a-zA-Z0-9._]*$}.} #' \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{identical.to}. #' @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(x, "unnamed") #' names(x) = letters[1:3] #' testNames(x, "unique") #' #' cn = c("Species", "Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width") #' assertNames(names(iris), permutation.of = cn) checkNames = function(x, type = "named", subset.of = NULL, must.include = NULL, permutation.of = NULL, identical.to = NULL, 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) } checkNamesCmp = function(x, subset.of, must.include, permutation.of, identical.to, disjunct.from) { if (!is.null(subset.of)) { qassert(subset.of, "S") if (anyMissing(match(x, subset.of))) return(sprintf("Must be a subset of set {%s}", paste0(subset.of, collapse = ","))) } if (!is.null(must.include)) { qassert(must.include, "S") if (anyMissing(match(must.include, x))) return(sprintf("Must include the elements {%s}", paste0(must.include, collapse = ","))) } if (!is.null(permutation.of)) { permutation.of = unique(qassert(permutation.of, "S")) if (length(x) != length(permutation.of) || !setequal(x, permutation.of)) return(sprintf("Must be a permutation of set {%s}", paste0(permutation.of, collapse = ","))) } if (!is.null(identical.to)) { qassert(identical.to, "S") if (!identical(x, identical.to)) return(sprintf("Must be a identical to (%s)", paste0(identical.to, collapse = ","))) } if (!is.null(disjunct.from)) { if (any(x %in% disjunct.from)) return(sprintf("Must be disjunct from (%s)", paste0(disjunct.from, collapse = ","))) } 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/matchArg.R0000644000176200001440000000261313616076131014256 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/checkLogical.R0000644000176200001440000000242413616076131015100 0ustar liggesusers#' Check if an argument is a vector of type logical #' #' @templateVar fn Logical #' @template x #' @template na-handling #' @inheritParams checkVector #' @template null.ok #' @template checker #' @family basetypes #' @useDynLib checkmate c_check_logical #' @export #' @examples #' testLogical(TRUE) #' testLogical(TRUE, min.len = 1) checkLogical = function(x, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) { .Call(c_check_logical, x, any.missing, all.missing, len, min.len, max.len, unique, names, null.ok) } #' @export #' @rdname checkLogical check_logical = checkLogical #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkLogical assertLogical = makeAssertionFunction(checkLogical, c.fun = "c_check_logical", 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/checkFormula.R0000644000176200001440000000313713616076131015135 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/checkArray.R0000644000176200001440000000313413616076131014603 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/checkSubset.R0000644000176200001440000000375713616076131015005 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) } qassert(choices, "a") if (length(choices) == 0L) { if (length(x) == 0L) return(TRUE) return("Must be a subset of the empty set, i.e. also empty") } if (isTRUE(fmatch) && requireNamespace("fastmatch", quietly = TRUE)) match = fastmatch::fmatch if (!is.null(x) && ((!isSameType(x, choices) && !allMissing(x)) || anyMissing(match(x, choices)))) return(sprintf("Must be a subset of %s, but is %s", set_collapse(choices), set_collapse(x))) return(TRUE) } #' @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/checkNumber.R0000644000176200001440000000236513616076131014762 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/coalesce.R0000644000176200001440000000115113616076131014302 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/checkClass.R0000644000176200001440000000430013616076131014566 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/checkSetEqual.R0000644000176200001440000000371713616076131015257 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))) } else { if (isTRUE(fmatch) && requireNamespace("fastmatch", quietly = TRUE)) match = fastmatch::fmatch if ((!isSameType(x, y) && !allMissing(x)) || anyMissing(match(x, y)) || anyMissing(match(y, x))) return(sprintf("Must be equal to set %s, but is %s", set_collapse(y), set_collapse(x))) } return(TRUE) } #' @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/checkInt.R0000644000176200001440000000225213616076131014257 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/wfwl.R0000644000176200001440000000157213616076131013512 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/checkVector.R0000644000176200001440000000415613616076131014774 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 only missing values allowed? Default is \code{TRUE}. #' @param len [\code{integer(1)}]\cr #' Exact expected length of \code{x}. #' @param min.len [\code{integer(1)}]\cr #' Minimal length of \code{x}. #' @param max.len [\code{integer(1)}]\cr #' Maximal length of \code{x}. #' @param unique [\code{logical(1)}]\cr #' Must all values be unique? Default is \code{FALSE}. #' @param names [\code{character(1)}]\cr #' Check for names. See \code{\link{checkNamed}} for possible values. #' Default is \dQuote{any} which performs no check at all. #' Note that you can use \code{\link{checkSubset}} to check for a specific set of names. #' @template null.ok #' @template checker #' @family basetypes #' @family atomicvector #' @useDynLib checkmate c_check_vector #' @export #' @examples #' testVector(letters, min.len = 1L, any.missing = FALSE) checkVector = function(x, strict = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, names = NULL, null.ok = FALSE) { .Call(c_check_vector, x, strict, any.missing, all.missing, len, min.len, max.len, unique, names, null.ok) } #' @export #' @rdname checkVector check_vector = checkVector #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkVector assertVector = makeAssertionFunction(checkVector, c.fun = "c_check_vector", 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/checkCharacter.R0000644000176200001440000000531713616076131015426 0ustar liggesusers#' Check if an argument is a vector of type character #' #' @templateVar fn Character #' @template x #' @template na-handling #' @inheritParams checkVector #' @param pattern [\code{character(1L)}]\cr #' Regular expression as used in \code{\link[base]{grepl}}. #' All non-missing elements of \code{x} must comply to this pattern. #' @param fixed [\code{character(1)}]\cr #' Substring to detect in \code{x}. Will be used as \code{pattern} in \code{\link[base]{grepl}} #' with option \code{fixed} set to \code{TRUE}. #' All non-missing elements of \code{x} must contain this substring. #' @param ignore.case [\code{logical(1)}]\cr #' See \code{\link[base]{grepl}}. Default is \code{FALSE}. #' @param min.chars [\code{integer(1)}]\cr #' Minimum number of characters for each element of \code{x}. #' @template sorted #' @template null.ok #' @template checker #' @family basetypes #' @useDynLib checkmate c_check_character #' @export #' @examples #' testCharacter(letters, min.len = 1, any.missing = FALSE) #' testCharacter(letters, min.chars = 2) #' testCharacter("example", pattern = "xa") checkCharacter = function(x, min.chars = NULL, pattern = NULL, fixed = NULL, ignore.case = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, null.ok = FALSE) { .Call(c_check_character, x, min.chars, any.missing, all.missing, len, min.len, max.len, unique, sorted, names, null.ok) %and% checkCharacterPattern(x, pattern, fixed, ignore.case) } checkCharacterPattern = function(x, pattern = NULL, fixed = NULL, ignore.case = FALSE) { if (!is.null(x)) { if (!is.null(pattern)) { qassert(pattern, "S1") ok = grepl(pattern, x[!is.na(x)], fixed = FALSE, ignore.case = ignore.case) if (!all(ok)) return(sprintf("Must comply to pattern '%s'", pattern)) } if (!is.null(fixed)) { qassert(fixed, "S1") ok = grepl(fixed, x[!is.na(x)], fixed = TRUE, ignore.case = ignore.case) if (!all(ok)) return(sprintf("Must contain substring '%s'", fixed)) } } return(TRUE) } #' @export #' @rdname checkCharacter check_character = checkCharacter #' @export #' @include makeAssertion.R #' @template assert #' @rdname checkCharacter assertCharacter = makeAssertionFunction(checkCharacter, 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/checkRaw.R0000644000176200001440000000274413616076131014264 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/checkMultiClass.R0000644000176200001440000000304513616076131015606 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/NEWS.md0000644000176200001440000002671213616076131013310 0ustar liggesusers# 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/MD50000644000176200001440000003165113616662435012530 0ustar liggesusersbbc1150487c5c347692c50a69a123868 *DESCRIPTION 12150ebd522453dd3d7ba23b88973fe4 *LICENSE 03fb58c31c6b4b0703d150ecfa3ca12f *NAMESPACE 7fa7b39a642c170834eeb6d8129ede26 *NEWS.md f0fc2aeb92b3d2014f6357308fd80954 *R/AssertCollection.R a7fc65b769f9477797c56c8c2af12339 *R/allMissing.R d4b005e269d2845ff89bed357a4e3d5f *R/anyInfinite.R 4e5ba9b259b46bf424e3ce1000f68e90 *R/anyMissing.R 65edb5b66b8a66217713a6aa2df5f3b9 *R/anyNaN.R 774b3adcff4d49e312551dd281796a7c *R/asInteger.R 5046484485b160eff76c53ce1b23d38c *R/assert.R 06764f178bb0c2ca5bee8e7b6fb8fffd *R/checkAccess.R 69c994dac41fd093ff563a26df3372f6 *R/checkArray.R 8ecb3b4404a10ebf34b14be8ca516f51 *R/checkAtomic.R 3159ba95fc55e588ec02cf8e7fba3013 *R/checkAtomicVector.R 3fb6268281e4951204e293ab9668649b *R/checkCharacter.R 151f0057a97f8f20a2f3a61167f0f9f6 *R/checkChoice.R a945f3af2d90972f130c065f257a7e0d *R/checkClass.R 0d31cab8cdedff09541280e73fa058e7 *R/checkComplex.R 18688628d514c3133a47a051a32db116 *R/checkCount.R feb55ad8dea59309a36e56ccb9f725c5 *R/checkDataFrame.R d873257563cd589aaefdf1caa0a15831 *R/checkDataTable.R a4b88ea5f0a5d376d714c8cd34399d74 *R/checkDate.R c4c754647890c65da8f0044aef972837 *R/checkDirectoryExists.R b28b9d20fbbe9f38ae338665c14e823e *R/checkDisjunct.R 8909d3fe10f6a3689416c59fc6e26bfb *R/checkDouble.R fcdac8476ee20a613a516e9d1a220456 *R/checkEnvironment.R 54378cb2e553ea81ec2ac5d3231e326d *R/checkFALSE.R c0fcb02d9a4371a5c8ab2d0bca42ab70 *R/checkFactor.R a3a1ffaf280f2aa8ccae0269e4011f71 *R/checkFileExists.R 1702c4c5319656458a29dcf2a583ada7 *R/checkFlag.R 6f2523dcdca0680cc9ff420af17b2dbd *R/checkFormula.R d12ec20b440da7dbc5001d4a53b3478f *R/checkFunction.R 010d3b94c18be3104ce67320710dadd1 *R/checkInt.R d8ed036b51855aee4818196ce2b8dde2 *R/checkInteger.R f42c1237ac7f777ea1adadeaf0726536 *R/checkIntegerish.R 79d8ce9b14cf9306efff8cc6d7e0f32d *R/checkList.R 20f906f515f9f418c4e14b4340447495 *R/checkLogical.R 63d09cf4637e1bf8e8d81e37966c10e1 *R/checkMatrix.R 1b11b632a897f9353f3045c17f53e225 *R/checkMultiClass.R e8144ea521e066f5f751e95a9f59aa29 *R/checkNamed.R f46dcc096f670d36550e76029e833989 *R/checkNames.R 083d948350010062f75349a480a14d04 *R/checkNull.R c5d319670af3c71df9f9d7779edec535 *R/checkNumber.R 42a246e84438a1d8d628d2cda1ee4405 *R/checkNumeric.R 489644560780caf623590aa036f74ef9 *R/checkOS.R 41fe8fdbd5a9111867a3688f0baeb8a2 *R/checkPOSIXct.R 7e11bb05730eaabb63879fc3ceedcc69 *R/checkPathForOutput.R 170499ac19008ffd1efe87e52bb051d6 *R/checkR6.R 2642a4b36862ab6b9b06801163903593 *R/checkRaw.R ecf6b98d81325dce56c793e946c9e7ab *R/checkScalar.R 67ac61f829b322b59e3ac15b47fa3df1 *R/checkScalarNA.R 8c74ec2e3fb9eeafcb0a053648c8b392 *R/checkSetEqual.R 63120bf7d2e138c6da45136266780f93 *R/checkString.R c6c76edb40ccaffb7eb86fb4fb337355 *R/checkSubset.R 37a8a17ca8652cb5feb1bc9c3958e98e *R/checkTRUE.R 34174c8e2ee8b61dbeebfbe37ba30fb4 *R/checkTibble.R 9d5fcb6faffb32a867923f8b0eca175a *R/checkVector.R 80ae11a07596493bea7960e2eb65dd73 *R/coalesce.R 1134a527d20d312744b933c2e8b48a14 *R/helper.R bd5ff342b970d92b9fa99f437af82b72 *R/isIntegerish.R 14e817a17e88758d845cbc0c68353586 *R/makeAssertion.R 895be2cd520376a63694d8be0fce3bc0 *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 c4211d2b52bc0c8cca7dbb2510ca7d26 *R/zzz.R b9b759f3c4b9ae7e2a2013f8b05d4d9c *README.md 9a70a3c201b50cd5d43482ee7c54cacf *build/vignette.rds 1fc7d9ccd9c68a9f21d76744c19fd6ed *inst/CITATION ad637253c5d187966d7f9e86257c3e37 *inst/doc/checkmate.R 4d75f947464dca70883f20a722413fca *inst/doc/checkmate.Rmd 68d8c7404391af808e724755718d52b4 *inst/doc/checkmate.html 17980f8c135aeb8eb2e2ccacb2beb602 *inst/doc/tinytest.R 3fb1895852b5c2593fa41aa6e7050ca6 *inst/doc/tinytest.Rmd 7ce51f48fb403ad91de108514703c2ce *inst/doc/tinytest.html 022139fefe30297f3f1ef95ae27f3901 *inst/include/checkmate.h 7455ff6681ad01c81b9fe547128ec5d3 *inst/include/checkmate_stub.c 570556c5f559df4b9cbc2388e9138da9 *man/AssertCollection.Rd ed7f80b05a99aa497b5c64d92afd8024 *man/anyInfinite.Rd b52205c5c2f8b48e1b2e24d3154902d3 *man/anyMissing.Rd 5a8da757d242d5d2ff28254575a4adcf *man/anyNaN.Rd 4b51d262a784bebee43dd524acde1fe1 *man/asInteger.Rd 4a3d0c2113382a72083a812be3d2a9df *man/assert.Rd 87647c04f2fa5c8eb0f1b76da7a13181 *man/checkAccess.Rd 43f2a247c94102a9249ec9657db9d56e *man/checkArray.Rd cd9f5df815cc7841b2e8d7f7f0e05557 *man/checkAtomic.Rd f238607ef814d231bac7e35a9a681c6f *man/checkAtomicVector.Rd 01ab5a8ae7d0e123006e80984c0e2d9d *man/checkCharacter.Rd b5bff178caefc4e91db82173a914d657 *man/checkChoice.Rd d25b83527df8f30e8de7d2d923944be2 *man/checkClass.Rd d971f700252c6696a857e455c99919dc *man/checkComplex.Rd 97e195598cabee769e8b0144add30090 *man/checkCount.Rd 64f47ca96091b8450cf1be2ca8d6f7cd *man/checkDataFrame.Rd 326b1bebb8c76a2b4741990c34a324e4 *man/checkDataTable.Rd 6bbf4ee4908100dfdd2ab121ac643c11 *man/checkDate.Rd 9a98aca0b12fe41e7355455be192d825 *man/checkDirectoryExists.Rd 9914731bccb0d099d7755319074955ab *man/checkDisjunct.Rd 7189457ddb5784605fe13497c57edeb0 *man/checkDouble.Rd 9141fb7d7b5f8b71ed961238e9caf40d *man/checkEnvironment.Rd 99ecc1948754c7b940306be3ee274d2f *man/checkFALSE.Rd 215f9d7cc7b3a40af6dec273d112754f *man/checkFactor.Rd c1817c387ffb40a81317014818ba7093 *man/checkFileExists.Rd 731b230f4cdc94a90a11ef5090e0e49b *man/checkFlag.Rd 3409f2868d03fd96114a903e74ad1792 *man/checkFormula.Rd 37c9ff58649afc23c966a956702dc29a *man/checkFunction.Rd 08f8f91657fbc67f50015c9411ae7a7e *man/checkInt.Rd 827689983faf11f36d675aa53df35137 *man/checkInteger.Rd bbb408cb0015fbf194747004e80602de *man/checkIntegerish.Rd 0e2255048b3666a7fcbfc16c017c6bcd *man/checkList.Rd ca991052b492acd313d0ddc25ae20275 *man/checkLogical.Rd 487b04a08ec745377496804d22a09548 *man/checkMatrix.Rd af27efd0c3c58676ca0334c4e0e3f333 *man/checkMultiClass.Rd d1991c62d2c9aa51748391c4c14721ae *man/checkNamed.Rd 73864b1e7418a23b7f69ce7fbf60eeed *man/checkNames.Rd 951b5ca24a49182f22c0a901ef943e3b *man/checkNull.Rd a9839bf7db5e6398094633a7860224bb *man/checkNumber.Rd 3fcdc336eb3e4cf81c9363abd24b5489 *man/checkNumeric.Rd ff76d6bf66451a0b7f32457df46ccaa2 *man/checkOS.Rd 5b37dfb57d80cfc657db92253d742958 *man/checkPOSIXct.Rd 6ca205d2a8934b9047fc9506918a8f95 *man/checkPathForOutput.Rd e722372c33c876e5e9833c3163b244e7 *man/checkR6.Rd 132845852278b7d629666312664868a3 *man/checkRaw.Rd 16dd59679fbc1e8876a0e74c1320233f *man/checkScalar.Rd 413ced4af84d08e6e419bb4a9166ee8a *man/checkScalarNA.Rd 29948b0284e678b14cf12863f59b8ed5 *man/checkSetEqual.Rd 13f97f610a8b5bc194581158585d0c26 *man/checkString.Rd 57ab6a7eaaf6f0382b7758cbad4e78c8 *man/checkSubset.Rd 44531cf5d2a63326c9e5f21e7a181c56 *man/checkTRUE.Rd ebb8eafced78e0cdfa03f93868573394 *man/checkTibble.Rd 083e07ed43eed004b091493f5a545ab1 *man/checkVector.Rd acf754d9000d810ba6e7f0d83d5342f9 *man/checkmate-package.Rd df830e7a73a97a9dcce66037219a92ab *man/coalesce.Rd 1bc40e14761aebef47147b73a5b58f89 *man/makeAssertion.Rd 494c2bc1746770cfccdafd2402f7c4f0 *man/makeExpectation.Rd a8630d8c55ee8d589b18be1d96a7bfb7 *man/makeTest.Rd 5da6ef4e2155034d75d6c4f9e7825b9c *man/matchArg.Rd e38f063426b7e5578701b39b5e28f8e3 *man/qassert.Rd f2171852fe8b8898bb1ed39d778ea210 *man/qassertr.Rd 04c13e4f11622873e34f735f404b11ce *man/register_test_backend.Rd c7160018ecdaf8c566838d3f71bc9b76 *man/vname.Rd 5ca43dddbda998d18889073324aae733 *man/wf.Rd 6767eec467f48ee13080d960c00867c0 *src/Makevars 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 238e955a3cd9dadb9f2078461fa97337 *src/checks.c d928ab64d7709ec73d0cbdb4ed549227 *src/checks.h 7835d63c8aaa237e87625c672042d321 *src/find_min_nchar.c 0636d9620a849431cba8d1d8651a6fb0 *src/find_min_nchar.h e84db1dc86df9cc8641179dd1e2ff3a0 *src/guess_type.c 626cdf5752ff0c365859428212510bfb *src/guess_type.h 55cbac6b20cf11577111b79d858defab *src/helper.c 3c25aa3d8755803c7f526d8a20e39662 *src/helper.h 2ed589157cb56709adb47fde8e77143b *src/init.c e13d22b6d12ae799a93b459587376454 *src/integerish.c 8efb31a0360216fdee5a63aa41c3ce93 *src/integerish.h f9625f42d59b7788902c0b0ca6eb7539 *src/is_sorted.c eccffa05125008d99e94d7ad36207cdf *src/is_sorted.h c261b5aaeac38dd000358df6d0c440b5 *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 ddaec2c7773e4d847cd1c41ce8747e07 *tests/testthat/test_assert.R 7b1fc897c76160a3e179c3b24148b657 *tests/testthat/test_checkArray.R 52088640fa738f4ab7e657e8b9b4cd02 *tests/testthat/test_checkAtomic.R ad416dbe956f3e6eb38ff46f77a4d8b1 *tests/testthat/test_checkAtomicVector.R 5cb691179dd2d3b461004eaf071b3c72 *tests/testthat/test_checkCharacter.R fdd0570044731f9e1907dc67c161eb49 *tests/testthat/test_checkChoice.R 6e93d0ffa46edae7777031821743ee3f *tests/testthat/test_checkClass.R 2501bf94e2f24021d01db9931f0f0e5d *tests/testthat/test_checkComplex.R f65d16c4f9802c45ff62c9ea264c5a73 *tests/testthat/test_checkCount.R 6ce6297d3710e3f7a50058a7a195539c *tests/testthat/test_checkDataFrame.R 57c3ad4acacfa42937790bf886a47aee *tests/testthat/test_checkDataTable.R 313830eabfe3dd1dee3fbf97de82dac6 *tests/testthat/test_checkDate.R e573b8f86b90294c92e5b791fa688a78 *tests/testthat/test_checkDisjunct.R d2f9c79ab6106324b4a8aa99e93f107e *tests/testthat/test_checkDouble.R 34c6dc60267982609546dfc50cdc58a5 *tests/testthat/test_checkEnvironment.R f7c6ce89bbbd44374eedaef0eef2b0ce *tests/testthat/test_checkFALSE.R d48dcd64af88c011a8b25197d3ac5bdf *tests/testthat/test_checkFactor.R f96af114d15103662437e59c71f229a1 *tests/testthat/test_checkFilesystem.R 2ca8bc06283a7c62bdd32f28ccdbda2a *tests/testthat/test_checkFlag.R 05785cb9cb39155726790723627b81f9 *tests/testthat/test_checkFormula.R 8f827cf646493433f5ea34dbb5a2607b *tests/testthat/test_checkFunction.R e08ef1e58036d81332bfc7df997154c5 *tests/testthat/test_checkInt.R ac02e0959d9c6a13c2796e396d93359d *tests/testthat/test_checkInteger.R b0d516944eb07ee5843bb78f4684cf75 *tests/testthat/test_checkIntegerish.R 2091d6755da41e6930331e44d509898b *tests/testthat/test_checkList.R edd75ed2d26e8ab74c186bff3511a403 *tests/testthat/test_checkLogical.R b05f4e7d4de6bf79cb2fe2adf8368534 *tests/testthat/test_checkMatrix.R 05ce05ad041b5f6c15a8349fe3037861 *tests/testthat/test_checkMultiClass.R 66f9ae42e0364d41599d2f7d15d3f85c *tests/testthat/test_checkNames.R 5ca56038ba855cffb5996db49724663b *tests/testthat/test_checkNull.R 522c310bf5964325aff7e7f94b89c8c8 *tests/testthat/test_checkNumber.R 4d044204956f074b7a843a7c59239417 *tests/testthat/test_checkNumeric.R af4d804926a342f32ea132c81eb0e9f3 *tests/testthat/test_checkOS.R 5deadc9354cc2d67cb28dd486eb67b26 *tests/testthat/test_checkPOSIXct.R 0569420355d062441f913ecdd9c2a374 *tests/testthat/test_checkR6.R 51166aa5b8f1b686d0a9739d93550a18 *tests/testthat/test_checkRaw.R de75d8d474ee541b05666065f39378fd *tests/testthat/test_checkScalar.R 97f0622df0ea56467eecde699a8f5ba6 *tests/testthat/test_checkScalarNA.R a3c9f00904c8ba7ffb79ee5fb1b4437e *tests/testthat/test_checkSetEqual.R 1bd8d79f850e7cd2d8a589f57cf720ec *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 b9bf6ed945609356dd7df579812eb9a9 *tests/testthat/test_qassert.R 10f26bde50eeb476573cf51c064343a6 *tests/testthat/test_qassertr.R 98d5ba13378e03edbc92debb3f37772e *tests/testthat/test_wf.R 4d75f947464dca70883f20a722413fca *vignettes/checkmate.Rmd 3fb1895852b5c2593fa41aa6e7050ca6 *vignettes/tinytest.Rmd checkmate/inst/0000755000176200001440000000000013616535121013156 5ustar liggesuserscheckmate/inst/doc/0000755000176200001440000000000013616535121013723 5ustar liggesuserscheckmate/inst/doc/tinytest.R0000644000176200001440000000021613616535121015730 0ustar liggesusers## ----------------------------------------------------------------------------- library("tinytest") library("checkmate") using("checkmate") checkmate/inst/doc/tinytest.html0000644000176200001440000002273113616535121016501 0ustar liggesusers Setup tinytest

Setup tinytest

Michel Lang

2020-02-05

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/inst/doc/checkmate.R0000644000176200001440000001277313616535121016004 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/checkmate.html0000644000176200001440000032035013616535121016540 0ustar liggesusers Checkmate

Checkmate

Michel Lang

2020-02-05

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

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

Enter checkmate.

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

Intro

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

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

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

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

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

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

Function overview

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

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

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

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

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

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

In case you miss flexibility

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

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

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

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

Argument Checks for the Lazy

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

checkmate as testthat extension

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

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

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

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

Speed considerations

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

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

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

Benchmark 1: Assert that x is a flag

library(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)
## Unit: microseconds
##    expr   min    lq     mean median     uq      max neval cld
##    r(x) 3.137 3.391 29.30048  3.484 3.6435 2561.891   100   a
##   cm(x) 2.257 2.478 14.89461  2.622 2.7495 1130.207   100   a
##  cmq(x) 1.496 1.640 11.08153  1.739 1.8525  849.814   100   a
autoplot(mb)
## Coordinate system already present. Adding new coordinate system, which will replace the existing one.

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) 15.639 16.4210 55.97355 16.8465 17.4790 3882.721   100   a
##   cm(x)  6.231  6.5905 17.35744  6.8870  7.1920  955.978   100   a
##  cmq(x)  6.299  6.6545 15.22232  6.8495  7.0295  819.705   100   a
autoplot(mb)
## Coordinate system already present. Adding new coordinate system, which will replace the existing one.

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) 1286.972 1320.4990 1424.82785 1371.4105 1428.7495 4531.028   100   b
##   cm(x)   68.164   70.8985   85.41703   73.7685   77.3755  890.016   100  a 
##  cmq(x)   82.929   86.4200   98.53113   90.2655   93.1135  839.488   100  a
autoplot(mb)
## Coordinate system already present. Adding new coordinate system, which will replace the existing one.

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) 80.901 85.2400 118.5151 87.607 92.262 2996.602   100   b
##   cm(x) 20.973 22.3405  39.4694 23.245 24.806 1128.040   100  a 
##  cmq(x) 12.972 13.6090  23.0715 14.171 14.913  861.294   100  a
autoplot(mb)
## Coordinate system already present. Adding new coordinate system, which will replace the existing one.

# checkmate tries to stop as early as possible
x$a[1] = NA
mb = microbenchmark(r(x), cm(x), cmq(x))
print(mb)
## Unit: microseconds
##    expr    min      lq     mean  median      uq     max neval cld
##    r(x) 80.389 83.5725 89.72053 85.8405 89.1400 380.493   100   c
##   cm(x)  5.862  6.6600  7.83138  7.7150  8.3435  30.829   100  b 
##  cmq(x)  1.004  1.1790  1.63684  1.4705  1.9945   7.321   100 a
autoplot(mb)
## Coordinate system already present. Adding new coordinate system, which will replace the existing one.

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) 28.219 29.1210 30.42030 29.4565 30.3535   45.163   100  ab
##    cm(x.sexp) 12.004 12.5320 21.26764 12.8390 13.2845  847.534   100  ab
##   r(x.altrep) 36.237 37.4785 63.11861 37.9735 38.8405 2475.242   100   b
##  cm(x.altrep)  3.217  3.5995  4.97869  3.8950  4.1180  114.613   100  a
autoplot(mb)
## Coordinate system already present. Adding new coordinate system, which will replace the existing one.

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 3.6.2 (2019-12-12)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Arch Linux
## 
## Matrix products: default
## BLAS/LAPACK: /usr/lib/libopenblas_haswellp-r0.3.7.so
## 
## locale:
##  [1] LC_CTYPE=de_DE.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=de_DE.UTF-8        LC_COLLATE=C              
##  [5] LC_MONETARY=de_DE.UTF-8    LC_MESSAGES=de_DE.UTF-8   
##  [7] LC_PAPER=de_DE.UTF-8       LC_NAME=C                 
##  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
## [11] LC_MEASUREMENT=de_DE.UTF-8 LC_IDENTIFICATION=C       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] microbenchmark_1.4-7 ggplot2_3.2.1        checkmate_2.0.0     
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.3       pillar_1.4.3     compiler_3.6.2   tools_3.6.2     
##  [5] digest_0.6.23    evaluate_0.14    lifecycle_0.1.0  tibble_2.1.3    
##  [9] gtable_0.3.0     lattice_0.20-38  pkgconfig_2.0.3  rlang_0.4.4     
## [13] Matrix_1.2-18    yaml_2.2.1       mvtnorm_1.0-12   xfun_0.12       
## [17] withr_2.1.2      stringr_1.4.0    dplyr_0.8.4      knitr_1.27      
## [21] grid_3.6.2       tidyselect_1.0.0 glue_1.3.1       R6_2.4.1        
## [25] survival_3.1-7   rmarkdown_2.1    multcomp_1.4-12  TH.data_1.0-10  
## [29] farver_2.0.3     purrr_0.3.3      magrittr_1.5     codetools_0.2-16
## [33] MASS_7.3-51.4    splines_3.6.2    backports_1.1.5  scales_1.1.0    
## [37] htmltools_0.4.0  assertthat_0.2.1 colorspace_1.4-1 sandwich_2.5-1  
## [41] stringi_1.4.5    lazyeval_0.2.2   munsell_0.5.0    crayon_1.3.4    
## [45] zoo_1.8-7
checkmate/inst/doc/tinytest.Rmd0000644000176200001440000000217613616076131016261 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} 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.Rmd0000644000176200001440000003107513616076131016322 0ustar liggesusers--- title: "Checkmate" author: "Michel Lang" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{checkmate} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r,include=FALSE} library(checkmate) ``` Ever used an R function that produced a not-very-helpful error message, just to discover after minutes of debugging that you simply passed a wrong argument? Blaming the laziness of the package author for not doing such standard checks (in a dynamically typed language such as R) is at least partially unfair, as R makes theses types of checks cumbersome and annoying. Well, that's how it was in the past. Enter checkmate. Virtually **every standard type of user error** when passing arguments into function can be caught with a simple, readable line which produces an **informative error message** in case. A substantial part of the package was written in C to **minimize any worries about execution time overhead**. ## Intro As a motivational example, consider you have a function to calculate the faculty of a natural number and the user may choose between using either the stirling approximation or R's `factorial` function (which internally uses the gamma function). Thus, you have two arguments, `n` and `method`. Argument `n` must obviously be a positive natural number and `method` must be either `"stirling"` or `"factorial"`. Here is a version of all the hoops you need to jump through to ensure that these simple requirements are met: ```{r} fact <- function(n, method = "stirling") { if (length(n) != 1) stop("Argument 'n' must have length 1") if (!is.numeric(n)) stop("Argument 'n' must be numeric") if (is.na(n)) stop("Argument 'n' may not be NA") if (is.double(n)) { if (is.nan(n)) stop("Argument 'n' may not be NaN") if (is.infinite(n)) stop("Argument 'n' must be finite") if (abs(n - round(n, 0)) > sqrt(.Machine$double.eps)) stop("Argument 'n' must be an integerish value") n <- as.integer(n) } if (n < 0) stop("Argument 'n' must be >= 0") if (length(method) != 1) stop("Argument 'method' must have length 1") if (!is.character(method) || !method %in% c("stirling", "factorial")) stop("Argument 'method' must be either 'stirling' or 'factorial'") if (method == "factorial") factorial(n) else sqrt(2 * pi * n) * (n / exp(1))^n } ``` And for comparison, here is the same function using checkmate: ```{r} fact <- function(n, method = "stirling") { assertCount(n) assertChoice(method, c("stirling", "factorial")) if (method == "factorial") factorial(n) else sqrt(2 * pi * n) * (n / exp(1))^n } ``` ## Function overview The functions can be split into four functional groups, indicated by their prefix. If prefixed with `assert`, an error is thrown if the corresponding check fails. Otherwise, the checked object is returned invisibly. There are many different coding styles out there in the wild, but most R programmers stick to either `camelBack` or `underscore_case`. Therefore, `checkmate` offers all functions in both flavors: `assert_count` is just an alias for `assertCount` but allows you to retain your favorite style. The family of functions prefixed with `test` always return the check result as logical value. Again, you can use `test_count` and `testCount` interchangeably. Functions starting with `check` return the error message as a string (or `TRUE` otherwise) and can be used if you need more control and, e.g., want to grep on the returned error message. `expect` is the last family of functions and is intended to be used with the [testthat package](https://cran.r-project.org/package=testthat). All performed checks are logged into the `testthat` reporter. Because `testthat` uses the `underscore_case`, the extension functions only come in the underscore style. All functions are categorized into objects to check on the [package help page](https://mllg.github.io/checkmate/reference/checkmate-package). ## In case you miss flexibility You can use [assert](https://mllg.github.io/checkmate/reference/assert) to perform multiple checks at once and throw an assertion if all checks fail. Here is an example where we check that x is either of class `foo` or class `bar`: ```{r} f <- function(x) { assert( checkClass(x, "foo"), checkClass(x, "bar") ) } ``` Note that `assert(, combine = "or")` and `assert(, combine = "and")` allow to control the logical combination of the specified checks, and that the former is the default. ## Argument Checks for the Lazy The following functions allow a special syntax to define argument checks using a special format specification. E.g., `qassert(x, "I+")` asserts that `x` is an integer vector with at least one element and no missing values. This very simple domain specific language covers a large variety of frequent argument checks with only a few keystrokes. You choose what you like best. * [qassert](https://mllg.github.io/checkmate/reference/qassert) * [qassertr](https://mllg.github.io/checkmate/reference/qassertr) ## checkmate as testthat extension To extend [testthat](https://cran.r-project.org/package=testthat), you need to IMPORT, DEPEND or SUGGEST on the `checkmate` package. Here is a minimal example: ```{r,eval=FALSE} # file: tests/test-all.R library(testthat) library(checkmate) # for testthat extensions test_check("mypkg") ``` Now you are all set and can use more than 30 new expectations in your tests. ```{r,eval=FALSE} test_that("checkmate is a sweet extension for testthat", { x = runif(100) expect_numeric(x, len = 100, any.missing = FALSE, lower = 0, upper = 1) # or, equivalent, using the lazy style: qexpect(x, "N100[0,1]") }) ``` ## Speed considerations In comparison with tediously writing the checks yourself in R (c.f. factorial example at the beginning of the vignette), R is sometimes a tad faster while performing checks on scalars. This seems odd at first, because checkmate is mostly written in C and should be comparably fast. Yet many of the functions in the `base` package are not regular functions, but primitives. While primitives jump directly into the C code, checkmate has to use the considerably slower `.Call` interface. As a result, it is possible to write (very simple) checks using only the base functions which, under some circumstances, slightly outperform checkmate. However, if you go one step further and wrap the custom check into a function to convenient re-use it, the performance gain is often lost (see benchmark 1). For larger objects the tide has turned because checkmate avoids many unnecessary intermediate variables. Also note that the quick/lazy implementation in `qassert`/`qtest`/`qexpect` is often a tad faster because only two arguments have to be evaluated (the object and the rule) to determine the set of checks to perform. Below you find some (probably unrepresentative) benchmark. But also note that this one here has been executed from inside `knitr` which is often the cause for outliers in the measured execution time. Better run the benchmark yourself to get unbiased results. ### Benchmark 1: Assert that `x` is a flag ```{r,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](http://r-pkgs.had.co.nz/src.html#clang) section in Hadley's Book "R Packages" or [WRE](https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Registering-native-routines). Here is a step-by-step guide to get you started: 1. Add `checkmate` to your "Imports" and "LinkingTo" sections in your DESCRIPTION file. 2. Create a stub C source file `"checkmate_stub.c"`, see 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/include/0000755000176200001440000000000013616076131014602 5ustar liggesuserscheckmate/inst/include/checkmate_stub.c0000644000176200001440000000077713616076131017742 0ustar liggesusers#include "checkmate.h" Rboolean qtest(SEXP x, const char *rule) { static Rboolean(*fun)(SEXP, const char *) = NULL; if (fun == NULL) fun = (Rboolean(*)(SEXP, const char *)) R_GetCCallable("checkmate", "qtest"); return fun(x, rule); } SEXP qassert(SEXP x, const char *rule, const char *name) { static SEXP(*fun)(SEXP, const char *, const char *) = NULL; if (fun == NULL) fun = (SEXP(*)(SEXP, const char *, const char *)) R_GetCCallable("checkmate", "qassert"); return fun(x, rule, name); } checkmate/inst/include/checkmate.h0000644000176200001440000000057013616076131016701 0ustar liggesusers#ifndef _CHECKMATE_H_ #define _CHECKMATE_H_ #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif Rboolean attribute_hidden qtest(SEXP x, const char *rule); SEXP attribute_hidden qassert(SEXP x, const char *rule, const char *name); #ifdef __cplusplus } #endif #endif checkmate/inst/CITATION0000644000176200001440000000054213616076131014315 0ustar liggesusersbibentry( bibtype = "Article", key = "checkmate", title = "{checkmate}: Fast Argument Checks for Defensive R Programming", author = person("Michel", "Lang"), journal = "The R Journal", year = 2017L, url = "https://journal.r-project.org/archive/2017/RJ-2017-028/index.html", pages = "437--445", volume = 9L, number = 1L ) # vim: ft=r