diff --git a/NAMESPACE b/NAMESPACE index 88498755c..8649c76d7 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -120,7 +120,12 @@ export(ds.vectorCalc) import(DSI) import(data.table) importFrom(DSI,datashield.connections_find) -importFrom(cli,cli_abort) +importFrom(cli, + cli_abort, + cli_inform, + cli_verbatim, + cli_warn +) importFrom(stats, as.formula, na.omit, diff --git a/R/checkClass.R b/R/checkClass.R index 08b89bd51..eb7436654 100644 --- a/R/checkClass.R +++ b/R/checkClass.R @@ -6,20 +6,19 @@ #' @param datasources a list of \code{\link[DSI]{DSConnection-class}} objects obtained after login. If the #' the default set of connections will be used: see \link[DSI]{datashield.connections_default}. #' @param obj a string character, the name of the object to check for. +#' @param call The frame to report the error from. #' @keywords internal #' @return a message or the class of the object if the object has the same class in all studies. #' #' -checkClass <- function(datasources=NULL, obj=NULL){ +checkClass <- function(datasources=NULL, obj=NULL, call=parent.frame()){ # check the class of the input object cally <- call("classDS", obj) classesBy <- DSI::datashield.aggregate(datasources, cally) classes <- unique(unlist(classesBy)) for (n in names(classesBy)) { if (!all(classes == classesBy[[n]])) { - message("The input data is not of the same class in all studies!") - message("Use the function 'ds.class' to verify the class of the input object in each study.") - stop(" End of process!", call.=FALSE) + cli_abort(c("{.val {obj}} must have the same class in all studies.", .describeStudyClasses(classesBy)), call = call) } } return(classes) diff --git a/R/ds.Boole.R b/R/ds.Boole.R index 881ebbb74..c0314feb5 100644 --- a/R/ds.Boole.R +++ b/R/ds.Boole.R @@ -104,32 +104,24 @@ #' ds.Boole<-function(V1=NULL, V2=NULL, Boolean.operator=NULL, numeric.output=TRUE, na.assign="NA",newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if user has provided the name of the column or scalar that holds V1 - if(is.null(V1)){ - stop("Please provide the name of the column or scalar that holds V1!", call.=FALSE) - } + .checkArgProvided(V1, "the name of the column or scalar that holds V1") # check if user has provided the name of a column or scalar holding V2 or has declared a scalar value: eg '3' - if(is.null(V2)){ - stop("Please provide the name of a column or scalar holding V2 or declare a scalar in character format: eg '3'", call.=FALSE) - } + .checkArgProvided(V2, "the name of a column or scalar that holds V2") # check if user has provided a Boolean operator in character format: eg '==' or '>=' or '<' or '!=' - if(is.null(Boolean.operator)){ - stop("Please provide a Boolean operator in character format: eg '==' or '>=' or '<' or '!='", call.=FALSE) - } + .checkArgProvided(Boolean.operator, "a Boolean operator in character format, such as \"==\" or \">=\"") #check if na.assign has legal value if(!(na.assign=="NA"||na.assign=="0"||na.assign=="1")){ - stop("Error: na.assign must be a character string taking value 'NA', '0' or '1'- if not specified default is 'NA'", call.=FALSE) + .abortInvalidChoice("na.assign", c("NA", "0", "1")) } # create a name by default if user did not provide a name for the new variable - if(is.null(newobj)){ - newobj <- "boole.newobj" - } + newobj <- .resolveNewobjName(newobj, "boole.newobj") #convert Boolean operator to numeric @@ -159,13 +151,11 @@ ds.Boole<-function(V1=NULL, V2=NULL, Boolean.operator=NULL, numeric.output=TRUE, } if(BO.n == 0){ - stop(paste0("An unrecognized Boolean operator, ", Boolean.operator, ", has provide"), call.=FALSE) + .abortInvalidChoice("Boolean.operator", c("==", "!=", "<", "<=", ">", ">=")) } # if no value spcified for output object, then specify a default - if(is.null(newobj)){ - newobj <- paste0(V1,"_Boole") - } + newobj <- .resolveNewobjName(newobj, paste0(V1,"_Boole")) # CALL THE MAIN SERVER SIDE FUNCTION calltext <- call("BooleDS", V1, V2, BO.n, na.assign, numeric.output) diff --git a/R/ds.abs.R b/R/ds.abs.R index 625591a84..d07d82dd2 100644 --- a/R/ds.abs.R +++ b/R/ds.abs.R @@ -73,15 +73,11 @@ #' ds.abs <- function(x=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input object!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input object") - if(is.null(newobj)){ - newobj <- "abs.newobj" - } + newobj <- .resolveNewobjName(newobj, "abs.newobj") cally <- call("absDS", x) DSI::datashield.assign(datasources, newobj, cally) diff --git a/R/ds.asCharacter.R b/R/ds.asCharacter.R index 700b90b12..63df864af 100644 --- a/R/ds.asCharacter.R +++ b/R/ds.asCharacter.R @@ -56,15 +56,11 @@ #' ds.asCharacter <- function(x.name=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x.name)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x.name, "the name of the input vector") - if(is.null(newobj)){ - newobj <- "ascharacter.newobj" - } + newobj <- .resolveNewobjName(newobj, "ascharacter.newobj") calltext <- call("asCharacterDS", x.name) DSI::datashield.assign(datasources, newobj, calltext) diff --git a/R/ds.asDataMatrix.R b/R/ds.asDataMatrix.R index 9126b9fc0..a7d322ffb 100644 --- a/R/ds.asDataMatrix.R +++ b/R/ds.asDataMatrix.R @@ -55,15 +55,11 @@ #' ds.asDataMatrix <- function(x.name=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x.name)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x.name, "the name of the input vector") - if(is.null(newobj)){ - newobj <- "asdatamatrix.newobj" - } + newobj <- .resolveNewobjName(newobj, "asdatamatrix.newobj") calltext <- call("asDataMatrixDS", x.name) DSI::datashield.assign(datasources, newobj, calltext) diff --git a/R/ds.asFactor.R b/R/ds.asFactor.R index a8ae29f48..9e1a99871 100644 --- a/R/ds.asFactor.R +++ b/R/ds.asFactor.R @@ -188,16 +188,15 @@ ds.asFactor <- function(input.var.name=NULL, newobj.name=NULL, forced.factor.levels=NULL, fixed.dummy.vars=FALSE, baseline.level=1, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if user has provided the name of the column that holds the input variable - if(is.null(input.var.name)){ - stop("Please provide the name of the variable that is to be converted to a factor e.g. 'varname'", call.=FALSE) - } + .checkArgProvided(input.var.name, "the name of the variable to convert to a factor") # check if user has provided the name of the input variable in a correct character format if(!is.character(input.var.name)){ - stop("Please provide the name of the variable that is to be converted to a factor in character format e.g. 'varname'", call.=FALSE) + supplied <- .describeSupplied(input.var.name) # nolint: object_usage_linter. Used in the cli template + cli_abort("{.arg input.var.name} must be a character string, such as {.val varname}, not {supplied}.") } # if no output variable specified then provide a default name @@ -217,7 +216,9 @@ ds.asFactor <- function(input.var.name=NULL, newobj.name=NULL, forced.factor.lev failed.levels <- TRUE } if (failed.levels) { - stop("Failed to obtain levels: ", paste0(unlist(all.levels), collapse=", "), call. = TRUE) + messages <- unlist(all.levels) + bullets <- stats::setNames(paste0("{messages[", seq_along(messages), "]}"), rep("x", length(messages))) + cli_abort(c("Can't obtain the factor levels.", bullets)) } numstudies <- length(datasources) diff --git a/R/ds.asFactorSimple.R b/R/ds.asFactorSimple.R index fc092d352..1bcc0d6f2 100644 --- a/R/ds.asFactorSimple.R +++ b/R/ds.asFactorSimple.R @@ -24,16 +24,15 @@ #' ds.asFactorSimple <- function(input.var.name=NULL, newobj.name=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if user has provided the name of the column that holds the input variable - if(is.null(input.var.name)){ - stop("Please provide the name of the variable that is to be converted to a factor e.g. 'varname'", call.=FALSE) - } + .checkArgProvided(input.var.name, "the name of the variable to convert to a factor") # check if user has provided the name of the input variable in a correct character format if(!is.character(input.var.name)){ - stop("Please provide the name of the variable that is to be converted to a factor in character format e.g. 'varname'", call.=FALSE) + supplied <- .describeSupplied(input.var.name) # nolint: object_usage_linter. Used in the cli template + cli_abort("{.arg input.var.name} must be a character string, such as {.val varname}, not {supplied}.") } # if no output variable specified then provide a default name diff --git a/R/ds.asInteger.R b/R/ds.asInteger.R index bd5eb2921..b34fe567b 100644 --- a/R/ds.asInteger.R +++ b/R/ds.asInteger.R @@ -69,15 +69,11 @@ #' @export ds.asInteger <- function(x.name=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x.name)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x.name, "the name of the input vector") - if(is.null(newobj)){ - newobj <- "asinteger.newobj" - } + newobj <- .resolveNewobjName(newobj, "asinteger.newobj") calltext <- call("asIntegerDS", x.name) DSI::datashield.assign(datasources, newobj, calltext) diff --git a/R/ds.asList.R b/R/ds.asList.R index 516d51e39..88a4ea2d5 100644 --- a/R/ds.asList.R +++ b/R/ds.asList.R @@ -57,15 +57,11 @@ #' ds.asList <- function(x.name=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x.name)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x.name, "the name of the input vector") - if(is.null(newobj)){ - newobj <- "aslist.newobj" - } + newobj <- .resolveNewobjName(newobj, "aslist.newobj") datashield.assign(datasources, newobj, call("asListDS", x.name)) diff --git a/R/ds.asLogical.R b/R/ds.asLogical.R index 89dfb2556..cb8f66525 100644 --- a/R/ds.asLogical.R +++ b/R/ds.asLogical.R @@ -56,15 +56,11 @@ #' ds.asLogical <- function(x.name=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x.name)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x.name, "the name of the input vector") - if(is.null(newobj)){ - newobj <- "aslogical.newobj" - } + newobj <- .resolveNewobjName(newobj, "aslogical.newobj") calltext <- call("asLogicalDS", x.name) DSI::datashield.assign(datasources, newobj, calltext) diff --git a/R/ds.asMatrix.R b/R/ds.asMatrix.R index 1c97dbf1b..67cf1d48a 100644 --- a/R/ds.asMatrix.R +++ b/R/ds.asMatrix.R @@ -58,15 +58,11 @@ #' ds.asMatrix <- function(x.name=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x.name)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x.name, "the name of the input vector") - if(is.null(newobj)){ - newobj <- "asmatrix.newobj" - } + newobj <- .resolveNewobjName(newobj, "asmatrix.newobj") calltext <- call("asMatrixDS", x.name) DSI::datashield.assign(datasources, newobj, calltext) diff --git a/R/ds.asNumeric.R b/R/ds.asNumeric.R index 980a71176..7fadcfb55 100644 --- a/R/ds.asNumeric.R +++ b/R/ds.asNumeric.R @@ -70,15 +70,11 @@ #' ds.asNumeric <- function(x.name=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x.name)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x.name, "the name of the input vector") - if(is.null(newobj)){ - newobj <- "asnumeric.newobj" - } + newobj <- .resolveNewobjName(newobj, "asnumeric.newobj") calltext <- call("asNumericDS", x.name) DSI::datashield.assign(datasources, newobj, calltext) diff --git a/R/ds.assign.R b/R/ds.assign.R index c646e3785..473a614fd 100644 --- a/R/ds.assign.R +++ b/R/ds.assign.R @@ -57,16 +57,12 @@ #' ds.assign <- function(toAssign=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(toAssign)){ - stop("Please give the name of object to assign or an expression to evaluate and assign.!\n", call.=FALSE) - } + .checkArgProvided(toAssign, "the name of the object to assign or an expression to evaluate") # create a name by default if user did not provide a name for the new variable - if(is.null(newobj)){ - newobj <- "assign.newobj" - } + newobj <- .resolveNewobjName(newobj, "assign.newobj") # now do the business DSI::datashield.assign(datasources, newobj, as.symbol(toAssign)) diff --git a/R/ds.auc.R b/R/ds.auc.R index 8b16502b1..fd4985d6b 100644 --- a/R/ds.auc.R +++ b/R/ds.auc.R @@ -16,17 +16,13 @@ #' ds.auc <- function(pred=NULL, y=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # verify that 'pred' was set - if(is.null(pred)){ - stop("Please provide the name of the vector with predicted values", call.=FALSE) - } + .checkArgProvided(pred, "the name of the vector of predicted values") # verify that 'y' was set - if(is.null(y)){ - stop("Please provide the name of the outcome variable", call.=FALSE) - } + .checkArgProvided(y, "the name of the outcome variable") cally <- call('aucDS', pred, y) output <- DSI::datashield.aggregate(datasources, cally) diff --git a/R/ds.boxPlot.R b/R/ds.boxPlot.R index cb51d601f..68ea8fc76 100644 --- a/R/ds.boxPlot.R +++ b/R/ds.boxPlot.R @@ -87,20 +87,20 @@ ds.boxPlot <- function(x, variables = NULL, group = NULL, group2 = NULL, xlabel = "x axis", ylabel = "y axis", type = "pooled", datasources = NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # Ensure type is 'pooled' or 'split' if((length(type) == 1) && (! any(type %in% c("pooled", "split")))){ - stop("[type] can only be set to 'pooled' or 'split'") + .abortInvalidChoice("type", c("pooled", "split")) } # Determine class of x for dispatch cls <- datashield.aggregate(datasources, call("classDS", x)) - .checkClassConsistency(lapply(cls, function(study.class) list(class = study.class)), object_name = x) + .checkClassConsistency(lapply(cls, function(study.class) list(class = study.class)), objectName = x) cls <- unique(unlist(cls)) if(!any(c("numeric", "data.frame") %in% cls)){ - stop("The selected object is not a data frame nor a numerical vector") + cli_abort("{.arg x} must be a {.cls data.frame} or {.cls numeric} vector, not {.cls {cls}}.") } # Once all checks are passed, call the appropiate server functions diff --git a/R/ds.boxPlotGG.R b/R/ds.boxPlotGG.R index e562d9719..25f1d912e 100644 --- a/R/ds.boxPlotGG.R +++ b/R/ds.boxPlotGG.R @@ -24,7 +24,7 @@ ds.boxPlotGG <- function(x, group = NULL, group2 = NULL, xlabel = "x axis", ylabel = "y axis", type = "pooled", datasources = NULL){ x_var <- lower <- upper <- ymin <- ymax <- middle <- fill <- NULL - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) plot_data <- datashield.aggregate(datasources, call("boxPlotGGDS", data_table.name=x, group=group, group2=group2)) @@ -132,7 +132,7 @@ ds.boxPlotGG <- function(x, group = NULL, group2 = NULL, xlabel = "x axis", ylab plt <- do.call(gridExtra::grid.arrange, plt) } - else{stop("Invalid type")} + else{.abortInvalidChoice("type", c("pooled", "split"))} return(plt) diff --git a/R/ds.boxPlotGG_data_Treatment.R b/R/ds.boxPlotGG_data_Treatment.R index 84d32e1ab..204d21a2b 100644 --- a/R/ds.boxPlotGG_data_Treatment.R +++ b/R/ds.boxPlotGG_data_Treatment.R @@ -20,7 +20,7 @@ ds.boxPlotGG_data_Treatment <- function(table, variables, group = NULL, group2 = NULL, datasources = NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) datashield.assign.expr(datasources, "boxPlotRawData", call("boxPlotGG_data_TreatmentDS", table.name = table, variables = variables, group = group, group2 = group2)) diff --git a/R/ds.boxPlotGG_data_Treatment_numeric.R b/R/ds.boxPlotGG_data_Treatment_numeric.R index b80baca6d..066f1ca28 100644 --- a/R/ds.boxPlotGG_data_Treatment_numeric.R +++ b/R/ds.boxPlotGG_data_Treatment_numeric.R @@ -15,7 +15,7 @@ ds.boxPlotGG_data_Treatment_numeric <- function(vector, datasources = NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) datashield.assign.expr(datasources, "boxPlotRawDataNumeric", call("boxPlotGG_data_Treatment_numericDS", vector.name = vector)) diff --git a/R/ds.boxPlotGG_numeric.R b/R/ds.boxPlotGG_numeric.R index e3d4a679f..c666c0f86 100644 --- a/R/ds.boxPlotGG_numeric.R +++ b/R/ds.boxPlotGG_numeric.R @@ -12,7 +12,7 @@ ds.boxPlotGG_numeric <- function(x, xlabel = "x axis", ylabel = "y axis", type = "pooled", datasources = NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) ds.boxPlotGG_data_Treatment_numeric(x, datasources) diff --git a/R/ds.boxPlotGG_table.R b/R/ds.boxPlotGG_table.R index 936caf769..667f00a86 100644 --- a/R/ds.boxPlotGG_table.R +++ b/R/ds.boxPlotGG_table.R @@ -18,7 +18,7 @@ ds.boxPlotGG_table <- function(x, variables, group = NULL, group2 = NULL, xlabel = "x axis", ylabel = "y axis", type = "pooled", datasources = NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) ds.boxPlotGG_data_Treatment(x, variables, group, group2, datasources) diff --git a/R/ds.bp_standards.R b/R/ds.bp_standards.R index fe9b69fa5..efeb8bad7 100644 --- a/R/ds.bp_standards.R +++ b/R/ds.bp_standards.R @@ -32,32 +32,22 @@ ds.bp_standards <- function(sex=NULL, age=NULL, height=NULL, bp=NULL, systolic=TRUE, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # verify that 'sex' was set - if(is.null(sex)){ - stop("Please provide the name of the sex variable", call.=FALSE) - } + .checkArgProvided(sex, "the name of the sex variable") # verify that 'age' was set - if(is.null(age)){ - stop("Please provide the name of the age in months variable", call.=FALSE) - } + .checkArgProvided(age, "the name of the age in months variable") # verify that 'height' was set - if(is.null(height)){ - stop("Please provide the name of the height in cm variable", call.=FALSE) - } + .checkArgProvided(height, "the name of the height in cm variable") # verify that 'bp' was set - if(is.null(bp)){ - stop("Please provide the name of the blood pressure variable", call.=FALSE) - } + .checkArgProvided(bp, "the name of the blood pressure variable") # if no output object specified then provide a default name - if(is.null(newobj)){ - newobj <- "bp.newobj" - } + newobj <- .resolveNewobjName(newobj, "bp.newobj") # call the server-side assign function cally <- call('bp_standardsDS', sex, age, height, bp, systolic) diff --git a/R/ds.c.R b/R/ds.c.R index 8a9284139..519aec82b 100644 --- a/R/ds.c.R +++ b/R/ds.c.R @@ -60,16 +60,12 @@ #' ds.c <- function(x=NULL, newobj=NULL, datasources=NULL, classConsistencyCheck=TRUE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("x=NULL. Please provide the names of the objects to concatenate!", call.=FALSE) - } + .checkArgProvided(x, "the names of the objects to concatenate") # create a name by default if user did not provide a name for the new variable - if(is.null(newobj)){ - newobj <- "c.newobj" - } + newobj <- .resolveNewobjName(newobj, "c.newobj") if(classConsistencyCheck){ for(i in seq_along(x)){ diff --git a/R/ds.cbind.R b/R/ds.cbind.R index 1af1737a1..1c44c4559 100644 --- a/R/ds.cbind.R +++ b/R/ds.cbind.R @@ -117,66 +117,23 @@ #' ds.cbind <- function(x=NULL, DataSHIELD.checks=FALSE, force.colnames=NULL, newobj=NULL, datasources=NULL, notify.of.progress=FALSE, classConsistencyCheck=TRUE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide a vector of character strings holding the name of the input elements!", call.=FALSE) - } + .checkArgProvided(x, "a vector of the names of the input elements") if(DataSHIELD.checks){ # call the internal function that checks the input object(s) is(are) of the same legal class in all studies. if(classConsistencyCheck){ - for(i in 1:length(x)){ - typ <- checkClass(datasources, x[i]) - if(!('data.frame' %in% typ) & !('matrix' %in% typ) & !('factor' %in% typ) & !('character' %in% typ) & !('numeric' %in% typ) & !('integer' %in% typ) & !('logical' %in% typ)){ - stop("Only objects of type 'data.frame', 'matrix', 'numeric', 'integer', 'character', 'factor' and 'logical' are allowed.", call.=FALSE) - } - } - } - - # check that there are no duplicated column names in the input components - for(j in 1:length(datasources)){ - colNames <- list() - for(i in 1:length(x)){ - typ <- checkClass(datasources, x[i]) - if(any(typ %in% c('data.frame', 'matrix'))){ - colNames[[i]] <- ds.colnames(x=x[i], datasources=datasources[j]) - } - if(any(typ %in% c('factor', 'character', 'numeric', 'integer', 'logical'))){ - colNames[[i]] <- as.character(x[i]) - } - colNames <- unlist(colNames) - if(anyDuplicated(colNames) != 0){ - message("\n Warning: Some column names in study", j, "are duplicated and a suffix '.k' will be added to the kth replicate \n") - } - } + .checkObjectClasses(datasources, x) } - # check that the number of rows is the same in all componets to be cbind - for(j in 1:length(datasources)){ - nrows <- list() - for(i in 1:length(x)){ - typ <- checkClass(datasources, x[i]) - if(any(typ %in% c('data.frame', 'matrix'))){ - nrows[[i]] <- ds.dim(x=x[i], type='split', datasources=datasources[j])[[1]][1] - } - if(any(typ %in% c('factor', 'character', 'numeric', 'integer', 'logical'))){ - nrows[[i]] <- ds.length(x[i], type='split', datasources=datasources[j])[[1]] - } - } - nrows <- unlist(nrows) - if(any(nrows != nrows[1])){ - stop("The number of rows is not the same in all of the components to be cbind", call.=FALSE) - } - } + .checkMultiObjectConsistency(datasources, x) } # check newobj not actively declared as null - if(is.null(newobj)){ - newobj <- "cbind.newobj" - } + newobj <- .resolveNewobjName(newobj, "cbind.newobj") # CREATE THE VECTOR OF COLUMN NAMES colname.list <- list() @@ -189,7 +146,7 @@ ds.cbind <- function(x=NULL, DataSHIELD.checks=FALSE, force.colnames=NULL, newob next.class <- DSI::datashield.aggregate(datasources[std], calltext1) class.vector <- c(class.vector, next.class[[1]]) if (notify.of.progress){ - message("\n",j," of ", length(x), " elements to combine in step 1 of 2 in study ", std, "\n") + cli_inform("{j} of {length(x)} elements to combine in step 1 of 2 in {.val {names(datasources)[std]}}.") } } for(j in 1:length(x)){ @@ -197,14 +154,14 @@ ds.cbind <- function(x=NULL, DataSHIELD.checks=FALSE, force.colnames=NULL, newob if(class.vector[j]!="data.frame" && class.vector[j]!="matrix"){ colname.vector <- c(colname.vector, test.df) if (notify.of.progress){ - message("\n",j," of ", length(x), " elements to combine in step 2 of 2 in study ", std, "\n") + cli_inform("{j} of {length(x)} elements to combine in step 2 of 2 in {.val {names(datasources)[std]}}.") } }else{ calltext2 <- call('colnamesDS', test.df) df.names <- DSI::datashield.aggregate(datasources[std], calltext2) colname.vector <- c(colname.vector, df.names[[1]]) if (notify.of.progress){ - message("\n", j," of ", length(x), " elements to combine in step 2 of 2 in study ", std, "\n") + cli_inform("{j} of {length(x)} elements to combine in step 2 of 2 in {.val {names(datasources)[std]}}.") } } } @@ -212,7 +169,7 @@ ds.cbind <- function(x=NULL, DataSHIELD.checks=FALSE, force.colnames=NULL, newob } if (notify.of.progress){ - message("\nBoth steps in all studies completed\n") + cli_inform("Both steps completed in all studies.") } # prepare name vectors for transmission diff --git a/R/ds.changeRefGroup.R b/R/ds.changeRefGroup.R index 2ce6136aa..2cf9adddc 100644 --- a/R/ds.changeRefGroup.R +++ b/R/ds.changeRefGroup.R @@ -112,23 +112,17 @@ #' @export ds.changeRefGroup <- function(x=NULL, ref=NULL, newobj=NULL, reorderByRef=FALSE, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of a vector of type factor!", call.=FALSE) - } + .checkArgProvided(x, "the name of a factor") - if(is.null(ref)){ - stop(" You must indicate a reference level - set the parameter 'ref'.", call.=FALSE) - } + .checkArgProvided(ref, "a reference level") # create a name by default if user did not provide a name for the new variable - if(is.null(newobj)){ - newobj <- "changerefgroup.newobj" - } + newobj <- .resolveNewobjName(newobj, "changerefgroup.newobj") if(reorderByRef){ - warning("'reorderByRef' is set to TRUE. Please read the documentation for possible consequences!", call.=FALSE) + cli_warn(c("{.arg reorderByRef} is {.code TRUE}, so the levels of {.val {x}} are reordered.", "!" = "Results are invalid if the new vector is added to a table that isn't reordered in the same way.")) } # call the server side function that will recode the levels diff --git a/R/ds.class.R b/R/ds.class.R index 299950a47..d6474cb98 100644 --- a/R/ds.class.R +++ b/R/ds.class.R @@ -55,11 +55,9 @@ #' ds.class <- function(x=NULL, datasources=NULL) { - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input object!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input object") cally <- call('classDS', x) output <- DSI::datashield.aggregate(datasources, cally) diff --git a/R/ds.colnames.R b/R/ds.colnames.R index 571574217..d13cbd9b5 100644 --- a/R/ds.colnames.R +++ b/R/ds.colnames.R @@ -52,8 +52,8 @@ #' ds.colnames <- function(x=NULL, datasources=NULL) { - datasources <- .set_datasources(datasources) - .check_df_name_provided(x) + datasources <- .resolveDatasources(datasources) + .checkArgProvided(x, "the name of a data.frame or matrix") cally <- call("colnamesDS", x) column_names <- DSI::datashield.aggregate(datasources, cally) diff --git a/R/ds.completeCases.R b/R/ds.completeCases.R index 1a3d3f5aa..369d90404 100644 --- a/R/ds.completeCases.R +++ b/R/ds.completeCases.R @@ -73,15 +73,11 @@ #' ds.completeCases <- function(x1=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x1)){ - return("Error: x1 must be a character string naming a serverside data.frame, matrix or vector") - } + .checkArgProvided(x1, "a character string that names a server-side data.frame, matrix or vector") - if(is.null(newobj)){ - newobj <- paste0(x1,"_complete.cases") - } + newobj <- .resolveNewobjName(newobj, paste0(x1,"_complete.cases")) calltext <- call("completeCasesDS", x1) DSI::datashield.assign(datasources, newobj, calltext) diff --git a/R/ds.contourPlot.R b/R/ds.contourPlot.R index 94dfa21b0..a73182683 100644 --- a/R/ds.contourPlot.R +++ b/R/ds.contourPlot.R @@ -105,14 +105,10 @@ #' ds.contourPlot <- function(x=NULL, y=NULL, type='combine', show='all', numints=20, method="smallCellsRule", k=3, noise=0.25, datasources=NULL, classConsistencyCheck=FALSE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("x=NULL. Please provide the names of two numeric vectors!", call.=FALSE) - } - if(is.null(y)){ - stop("y=NULL. Please provide the names of two numeric vectors!", call.=FALSE) - } + .checkArgProvided(x, "the name of a numeric vector") + .checkArgProvided(y, "the name of a numeric vector") # Save par and setup reseting of par values old_par <- graphics::par(no.readonly = TRUE) @@ -120,7 +116,7 @@ ds.contourPlot <- function(x=NULL, y=NULL, type='combine', show='all', numints=2 # the argument method must be either "smallCellsRule" or "deterministic" or "probabilistic" if(method != 'smallCellsRule' & method != 'deterministic' & method != 'probabilistic'){ - stop('Function argument "method" has to be either "smallCellsRule" or "deterministic" or "probabilistic"', call.=FALSE) + .abortInvalidChoice("method", c("smallCellsRule", "deterministic", "probabilistic")) } # extract the variable names to be used as labels in the plot @@ -145,8 +141,8 @@ ds.contourPlot <- function(x=NULL, y=NULL, type='combine', show='all', numints=2 # call the server-side function that generates the x and y coordinates of the centroids anonymous.data <- datashield.aggregate(datasources, call("heatmapPlotDS", x.name=x, y.name=y, k=k, noise=noise, method.indicator=method.indicator)) if(classConsistencyCheck){ - .checkClassConsistency(anonymous.data, field = "class.x", object_name = x) - .checkClassConsistency(anonymous.data, field = "class.y", object_name = y) + .checkClassConsistency(anonymous.data, field = "class.x", objectName = x) + .checkClassConsistency(anonymous.data, field = "class.y", objectName = y) } pooled.points.x <- c() @@ -164,8 +160,8 @@ ds.contourPlot <- function(x=NULL, y=NULL, type='combine', show='all', numints=2 # call the server-side function that generates the x and y coordinates of the anonymous.data anonymous.data <- datashield.aggregate(datasources, call("heatmapPlotDS", x.name=x, y.name=y, k=k, noise=noise, method.indicator=method.indicator)) if(classConsistencyCheck){ - .checkClassConsistency(anonymous.data, field = "class.x", object_name = x) - .checkClassConsistency(anonymous.data, field = "class.y", object_name = y) + .checkClassConsistency(anonymous.data, field = "class.x", objectName = x) + .checkClassConsistency(anonymous.data, field = "class.y", objectName = y) } pooled.points.x <- c() @@ -206,8 +202,8 @@ ds.contourPlot <- function(x=NULL, y=NULL, type='combine', show='all', numints=2 # generate the grid density object to plot grid.density.obj <- datashield.aggregate(datasources, call("densityGridDS", x=x, y=y, limits=TRUE, x.min=x.global.min, x.max=x.global.max, y.min=y.global.min, y.max=y.global.max, numints=numints)) if(classConsistencyCheck){ - .checkClassConsistency(grid.density.obj, field = "class.x", object_name = x) - .checkClassConsistency(grid.density.obj, field = "class.y", object_name = y) + .checkClassConsistency(grid.density.obj, field = "class.x", objectName = x) + .checkClassConsistency(grid.density.obj, field = "class.y", objectName = y) } grid.density.obj <- lapply(grid.density.obj, function(r) r$grid) @@ -215,7 +211,7 @@ ds.contourPlot <- function(x=NULL, y=NULL, type='combine', show='all', numints=2 # print the number of invalid cells in each participating study for (i in 1:num.sources) { - message(stdnames[i],': ', names(dimnames(grid.density.obj[[i]])[2])) + cli_inform("{.val {stdnames[i]}}: {names(dimnames(grid.density.obj[[i]])[2])}") } Global.grid.density <- matrix(0, dim(grid.density.obj[[1]])[1], numcol-2) @@ -352,7 +348,7 @@ ds.contourPlot <- function(x=NULL, y=NULL, type='combine', show='all', numints=2 # plot a combined contour plot graphics::contour(x.zoomed,y.zoomed,z.zoomed, xlab=x.lab, ylab=y.lab, main="Contour Plot of the Pooled Data (zoomed)") }else{ - stop('Function argument "show" has to be either "all" or "zoomed"') + .abortInvalidChoice("show", c("all", "zoomed")) } } else if (type=='split') { @@ -361,8 +357,8 @@ ds.contourPlot <- function(x=NULL, y=NULL, type='combine', show='all', numints=2 # generate the grid density object to plot grid.density.obj <- datashield.aggregate(datasources, call("densityGridDS", x=x, y=y, limits=FALSE, x.min=NULL, x.max=NULL, y.min=NULL, y.max=NULL, numints=numints)) if(classConsistencyCheck){ - .checkClassConsistency(grid.density.obj, field = "class.x", object_name = x) - .checkClassConsistency(grid.density.obj, field = "class.y", object_name = y) + .checkClassConsistency(grid.density.obj, field = "class.x", objectName = x) + .checkClassConsistency(grid.density.obj, field = "class.y", objectName = y) } grid.density.obj <- lapply(grid.density.obj, function(r) r$grid) numcol <- dim(grid.density.obj[[1]])[2] @@ -410,7 +406,7 @@ ds.contourPlot <- function(x=NULL, y=NULL, type='combine', show='all', numints=2 # print the number of invalid cells in each participating study for (i in 1:num.sources) { - message(stdnames[i],': ', names(dimnames(grid.density.obj[[i]])[2])) + cli_inform("{.val {stdnames[i]}}: {names(dimnames(grid.density.obj[[i]])[2])}") } if(num.sources > 1){ @@ -501,7 +497,7 @@ ds.contourPlot <- function(x=NULL, y=NULL, type='combine', show='all', numints=2 graphics::contour(x.zoomed,y.zoomed,z.zoomed, xlab=x.lab, ylab=y.lab, main=title) }else{ - stop('Function argument "show" has to be either "all" or "zoomed"') + .abortInvalidChoice("show", c("all", "zoomed")) } } @@ -589,11 +585,11 @@ ds.contourPlot <- function(x=NULL, y=NULL, type='combine', show='all', numints=2 graphics::contour(x.zoomed,y.zoomed,z.zoomed, xlab=x.lab, ylab=y.lab, main="Contour Plot of the Pooled Data") }else{ - stop('Function argument "show" has to be either "all" or "zoomed"') + .abortInvalidChoice("show", c("all", "zoomed")) } } }else{ - stop('Function argument "type" has to be either "combine" or "split"') + .abortInvalidChoice("type", c("combine", "split")) } } diff --git a/R/ds.cor.R b/R/ds.cor.R index 6043a5113..be2b991fa 100644 --- a/R/ds.cor.R +++ b/R/ds.cor.R @@ -83,11 +83,9 @@ #' ds.cor <- function(x=NULL, y=NULL, type="split", datasources=NULL, classConsistencyCheck=TRUE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("x=NULL. Please provide the name of a matrix or dataframe or the names of two numeric vectors!", call.=FALSE) - } + .checkArgProvided(x, "the name of a matrix, data.frame or numeric vector") # name of the studies to be used in the output stdnames <- names(datasources) @@ -101,7 +99,7 @@ ds.cor <- function(x=NULL, y=NULL, type="split", datasources=NULL, classConsiste } if(!is.null(y) && any(output[[1]]$class %in% c("matrix", "data.frame"))){ - warning("x is a matrix or a dataframe; y will be ignored and a correlation matrix computed for x!") + cli_warn("{.arg x} is a {.cls matrix} or {.cls data.frame}, so {.arg y} is ignored and a correlation matrix is computed for {.arg x}.") } if (type=="split"){ @@ -164,7 +162,7 @@ ds.cor <- function(x=NULL, y=NULL, type="split", datasources=NULL, classConsiste n4 <- "Correlation Matrix" names(results) <- c(n1, n2, n3, n4) }else{ - stop('Function argument "type" has to be either "combine" or "split"', call.=FALSE) + .abortInvalidChoice("type", c("combine", "split")) } } diff --git a/R/ds.corTest.R b/R/ds.corTest.R index 78c802168..4e6ea7525 100644 --- a/R/ds.corTest.R +++ b/R/ds.corTest.R @@ -67,17 +67,13 @@ #' ds.corTest <- function(x=NULL, y=NULL, method="pearson", exact=NULL, conf.level=0.95, type='split', datasources=NULL, classConsistencyCheck=FALSE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("x=NULL. Please provide the names of the 1st numeric vector!", call.=FALSE) - } - if(is.null(y)){ - stop("y=NULL. Please provide the names of the 2nd numeric vector!", call.=FALSE) - } + .checkArgProvided(x, "the name of the first numeric vector") + .checkArgProvided(y, "the name of the second numeric vector") if(!(method %in% c("pearson", "kendall", "spearman"))){ - stop('Function argument "method" has to be either "pearson", "kendall" or "spearman"', call.=FALSE) + .abortInvalidChoice("method", c("pearson", "kendall", "spearman")) } # call the server side function @@ -132,7 +128,7 @@ ds.corTest <- function(x=NULL, y=NULL, method="pearson", exact=NULL, conf.level= return(out) } }else{ - stop('Function argument "type" has to be either "combine" or "split"', call.=FALSE) + .abortInvalidChoice("type", c("combine", "split")) } } diff --git a/R/ds.cov.R b/R/ds.cov.R index a35c9097a..b3115633e 100644 --- a/R/ds.cov.R +++ b/R/ds.cov.R @@ -100,11 +100,9 @@ #' ds.cov <- function(x=NULL, y=NULL, naAction='pairwise.complete', type="split", datasources=NULL, classConsistencyCheck=TRUE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("x=NULL. Please provide the name of a matrix or dataframe or the names of two numeric vectors!", call.=FALSE) - } + .checkArgProvided(x, "the name of a matrix, data.frame or numeric vector") # name of the studies to be used in the output stdnames <- names(datasources) @@ -118,7 +116,7 @@ ds.cov <- function(x=NULL, y=NULL, naAction='pairwise.complete', type="split", d } if(!is.null(y) && any(output[[1]]$class %in% c("matrix", "data.frame"))){ - warning("x is a matrix or a dataframe; y will be ignored and a covariance matrix computed for x!") + cli_warn("{.arg x} is a {.cls matrix} or {.cls data.frame}, so {.arg y} is ignored and a covariance matrix is computed for {.arg x}.") } if (type=="split"){ @@ -195,7 +193,7 @@ ds.cov <- function(x=NULL, y=NULL, naAction='pairwise.complete', type="split", d n5 <- "Error message" names(results) <- c(n1, n2, n3, n4, n5) }else{ - stop('Function argument "type" has to be either "combine" or "split"') + .abortInvalidChoice("type", c("combine", "split")) } } diff --git a/R/ds.dataFrame.R b/R/ds.dataFrame.R index c06322a50..a26145438 100644 --- a/R/ds.dataFrame.R +++ b/R/ds.dataFrame.R @@ -92,71 +92,26 @@ #' @export ds.dataFrame <- function(x=NULL, row.names=NULL, check.rows=FALSE, check.names=TRUE, stringsAsFactors=TRUE, completeCases=FALSE, DataSHIELD.checks=FALSE, newobj=NULL, datasources=NULL, notify.of.progress=FALSE, classConsistencyCheck=TRUE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the list that holds the input vectors!", call.=FALSE) - } + .checkArgProvided(x, "the name of the list that holds the input vectors") # create a name by default if user did not provide a name for the new variable - if(is.null(newobj)){ - newobj <- "dataframe.newobj" - } + newobj <- .resolveNewobjName(newobj, "dataframe.newobj") if(DataSHIELD.checks){ # call the internal function that checks the input object(s) is(are) of the same legal class in all studies. if(classConsistencyCheck){ - for(i in 1:length(x)){ - typ <- checkClass(datasources, x[i]) - if(!('data.frame' %in% typ) & !('matrix' %in% typ) & !('factor' %in% typ) & !('character' %in% typ) & !('numeric' %in% typ) & !('integer' %in% typ) & !('logical' %in% typ)){ - stop("Only objects of type 'data.frame', 'matrix', 'numeric', 'integer', 'character', 'factor' and 'logical' are allowed.", call.=FALSE) - } + .checkObjectClasses(datasources, x) } - } - - # check that there are no duplicated column names in the input components - for(j in 1:length(datasources)){ - colNames <- list() - for(i in 1:length(x)){ - typ <- checkClass(datasources, x[i]) - if(typ %in% c('data.frame', 'matrix')){ - colNames[[i]] <- ds.colnames(x=x[i], datasources=datasources[j]) - } - if(typ %in% c('factor', 'character', 'numeric', 'integer', 'logical')){ - colNames[[i]] <- as.character(x[i]) - } - colNames <- unlist(colNames) - if(anyDuplicated(colNames) != 0){ - message("\n Warning: Some column names in study", j, "are duplicated and a suffix '.k' will be added to the kth replicate \n") - } - } - } - # check that the number of rows is the same in all componets to be cbind - for(j in 1:length(datasources)){ - nrows <- list() - for(i in 1:length(x)){ - typ <- checkClass(datasources, x[i]) - if(typ %in% c('data.frame', 'matrix')){ - nrows[[i]] <- ds.dim(x=x[i], type='split', datasources=datasources[j])[[1]][1] - } - if(typ %in% c('factor', 'character', 'numeric', 'integer', 'logical')){ - nrows[[i]] <- ds.length(x[i], type='split', datasources=datasources[j])[[1]] - } - } - nrows <- unlist(nrows) - if(any(nrows != nrows[1])){ - stop("The number of rows is not the same in all of the input components", call.=FALSE) - } - } + .checkMultiObjectConsistency(datasources, x) } # check newobj not actively declared as null - if(is.null(newobj)){ - newobj <- "df_new" - } + newobj <- .resolveNewobjName(newobj, "df_new") # CREATE THE VECTOR OF COLUMN NAMES colname.list <- list() @@ -169,7 +124,7 @@ ds.dataFrame <- function(x=NULL, row.names=NULL, check.rows=FALSE, check.names=T next.class <- DSI::datashield.aggregate(datasources[std], calltext1) class.vector <- c(class.vector, next.class[[1]]) if (notify.of.progress){ - message("\n",j," of ", length(x), " elements to combine in step 1 of 2 in study ", std, "\n") + cli_inform("{j} of {length(x)} elements to combine in step 1 of 2 in {.val {names(datasources)[std]}}.") } } for(j in 1:length(x)){ @@ -177,14 +132,14 @@ ds.dataFrame <- function(x=NULL, row.names=NULL, check.rows=FALSE, check.names=T if(class.vector[j]!="data.frame" && class.vector[j]!="matrix"){ colname.vector <- c(colname.vector, test.df) if (notify.of.progress){ - message("\n",j," of ", length(x), " elements to combine in step 2 of 2 in study ", std, "\n") + cli_inform("{j} of {length(x)} elements to combine in step 2 of 2 in {.val {names(datasources)[std]}}.") } }else{ calltext2 <- call('colnamesDS', test.df) df.names <- DSI::datashield.aggregate(datasources[std], calltext2) colname.vector <- c(colname.vector, df.names[[1]]) if (notify.of.progress){ - message("\n", j," of ", length(x), " elements to combine in step 2 of 2 in study ", std, "\n") + cli_inform("{j} of {length(x)} elements to combine in step 2 of 2 in {.val {names(datasources)[std]}}.") } } } @@ -192,7 +147,7 @@ ds.dataFrame <- function(x=NULL, row.names=NULL, check.rows=FALSE, check.names=T } if (notify.of.progress){ - message("\nBoth steps in all studies completed\n") + cli_inform("Both steps completed in all studies.") } # prepare vectors for transmission diff --git a/R/ds.dataFrameSort.R b/R/ds.dataFrameSort.R index 3e41eccdd..df807c51b 100644 --- a/R/ds.dataFrameSort.R +++ b/R/ds.dataFrameSort.R @@ -83,7 +83,7 @@ ds.dataFrameSort<-function(df.name=NULL, sort.key.name=NULL, sort.descending=FALSE, sort.method="default", newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) if(is.null(sort.method)){ sort.method <- "default" @@ -105,7 +105,7 @@ ds.dataFrameSort<-function(df.name=NULL, sort.key.name=NULL, sort.descending=FAL sort.descending <- FALSE } - newobj <- .set_newobj_name(newobj, "dataframesort.newobj") + newobj <- .resolveNewobjName(newobj, "dataframesort.newobj") # Call to assign function calltext <- call("dataFrameSortDS", df.name, sort.key.name, sort.descending, sort.method) diff --git a/R/ds.dataFrameSubset.R b/R/ds.dataFrameSubset.R index c6603c41c..fb03be8d5 100644 --- a/R/ds.dataFrameSubset.R +++ b/R/ds.dataFrameSubset.R @@ -107,12 +107,10 @@ ds.dataFrameSubset<-function(df.name=NULL, V1.name=NULL, V2.name=NULL, Boolean.operator=NULL, keep.cols=NULL, rm.cols=NULL, keep.NAs=NULL, newobj=NULL, datasources=NULL, notify.of.progress=FALSE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if user has provided the name of the data.frame to be subsetted - if(is.null(df.name)){ - stop("Please provide the name of the data.frame to be subsetted as a character string: eg 'xxx'", call.=FALSE) - } + .checkArgProvided(df.name, "the name of the data.frame to subset") # check if user has provided the name of the column or scalar that holds V1. If not # have they instead provided a non.null keep.cols or non.null rm.cols argument @@ -122,7 +120,7 @@ ds.dataFrameSubset<-function(df.name=NULL, V1.name=NULL, V2.name=NULL, Boolean.o if(is.null(keep.cols)&&is.null(rm.cols)&&is.null(V1.name)) { - stop("Please provide the name of the column or scalar that holds V1 as a character string: eg 'xxx' or '3'", call.=FALSE) + cli_abort("{.arg V1.name} must name a column or scalar as a character string, not {.code NULL}, unless you are subsetting only columns.") } if((!is.null(keep.cols)||!is.null(rm.cols))&&is.null(V1.name)) @@ -138,7 +136,7 @@ ds.dataFrameSubset<-function(df.name=NULL, V1.name=NULL, V2.name=NULL, Boolean.o if(is.null(keep.cols)&&is.null(rm.cols)&&is.null(V2.name)) { - stop("Please provide the name of the column or scalar that holds V2 as a character string: eg 'xxx' or '3'", call.=FALSE) + cli_abort("{.arg V2.name} must name a column or scalar as a character string, not {.code NULL}, unless you are subsetting only columns.") } if((!is.null(keep.cols)||!is.null(rm.cols))&&is.null(V2.name)) @@ -148,15 +146,8 @@ ds.dataFrameSubset<-function(df.name=NULL, V1.name=NULL, V2.name=NULL, Boolean.o if(is.null(keep.cols)&&is.null(rm.cols)&&is.null(Boolean.operator)) { - message1<-"Unless you are only subsetting columns, please provide a" - message2<-"Boolean operator in character format: eg '==' or '>=' or '<' or '!='." - message3<-"However, if either keep.cols or rm.cols is non-null because you want" - message4<-"to subset columns and you specify both V1.name and V2.name as NULL (or 'ONES')" - message5<-"and Boolean.operator as NULL,ds.dataFrameSubset will subset out" - message6<-"the specified columns but will keep all rows." - error.message<-paste(message1,message2,message3,message4,message5,message6) - stop(error.message, call.=FALSE) + cli_abort(c("{.arg Boolean.operator} must be a Boolean operator in character format, such as {.val ==} or {.val >=}, not {.code NULL}, unless you are subsetting only columns.", "i" = "If {.arg keep.cols} or {.arg rm.cols} is set and {.arg V1.name}, {.arg V2.name} and {.arg Boolean.operator} are all {.code NULL}, the specified columns are subset and all rows are kept.")) } if((!is.null(keep.cols)||!is.null(rm.cols))&&is.null(Boolean.operator)) @@ -197,9 +188,7 @@ if(Boolean.operator == ">="){ } # if no value spcified for output object, then specify a default - if(is.null(newobj)){ - newobj <- "dataframesubset.newobj" - } + newobj <- .resolveNewobjName(newobj, "dataframesubset.newobj") if(!is.null(keep.cols)){ keep.cols<-paste0(as.character(keep.cols),collapse=",") @@ -221,13 +210,13 @@ if(!is.null(rm.cols)){ if (notify.of.progress) { if(num.messages==1){ - message("\nSource",s,"\n",return.warning.message[[s]][[1]],"\n") + cli_inform(c("Source {s}", "{return.warning.message[[s]][[1]]}")) }else{ - message("\nSource",s,"\n") + cli_inform("Source {s}") for(m in 1:(num.messages-1)){ - message(return.warning.message[[s]][[m]],"\n") + cli_inform("{return.warning.message[[s]][[m]]}") } - message(return.warning.message[[s]][[num.messages]],"\n") + cli_inform("{return.warning.message[[s]][[num.messages]]}") } } } diff --git a/R/ds.densityGrid.R b/R/ds.densityGrid.R index e2dcae6c1..9fe581127 100644 --- a/R/ds.densityGrid.R +++ b/R/ds.densityGrid.R @@ -86,15 +86,11 @@ #' ds.densityGrid <- function(x=NULL, y=NULL, numints=20, type='combine', datasources=NULL, classConsistencyCheck=FALSE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the numeric vector 'x'!", call.=FALSE) - } + .checkArgProvided(x, "the name of a numeric vector") - if(is.null(y)){ - stop("Please provide the name of the numeric vector 'y'!", call.=FALSE) - } + .checkArgProvided(y, "the name of a numeric vector") # name of the studies to be used in the plots' titles stdnames <- names(datasources) @@ -129,15 +125,15 @@ ds.densityGrid <- function(x=NULL, y=NULL, numints=20, type='combine', datasourc # generate the grid density object to plot grid.density.obj <- datashield.aggregate(datasources, call("densityGridDS", x=x, y=y, limits=TRUE, x.min=x.global.min, x.max=x.global.max, y.min=y.global.min, y.max=y.global.max, numints=numints)) if(classConsistencyCheck){ - .checkClassConsistency(grid.density.obj, field = "class.x", object_name = x) - .checkClassConsistency(grid.density.obj, field = "class.y", object_name = y) + .checkClassConsistency(grid.density.obj, field = "class.x", objectName = x) + .checkClassConsistency(grid.density.obj, field = "class.y", objectName = y) } grid.density.obj <- lapply(grid.density.obj, function(r) r$grid) numcol <- dim(grid.density.obj[[1]])[2] # print the number of invalid cells in each participating study for (i in 1:num.sources){ - message(stdnames[i],': ', names(dimnames(grid.density.obj[[i]])[2])) + cli_inform("{.val {stdnames[i]}}: {names(dimnames(grid.density.obj[[i]])[2])}") } Global.grid.density <- matrix(0, dim(grid.density.obj[[1]])[1], numcol-2) @@ -145,27 +141,25 @@ ds.densityGrid <- function(x=NULL, y=NULL, numints=20, type='combine', datasourc Global.grid.density <- Global.grid.density + grid.density.obj[[i]][,1:(numcol-2)] names(dimnames(Global.grid.density))[2] <- "Grid Density Matrix of the Pooled Data" } - # newline for some space between the previous messages and the matrix when it is displayed - message() return(Global.grid.density) }else{ if(type=="split"){ # generate the grid density object grid.density.obj <- datashield.aggregate(datasources, call("densityGridDS", x=x, y=y, limits=FALSE, x.min=NULL, x.max=NULL, y.min=NULL, y.max=NULL, numints=numints)) if(classConsistencyCheck){ - .checkClassConsistency(grid.density.obj, field = "class.x", object_name = x) - .checkClassConsistency(grid.density.obj, field = "class.y", object_name = y) + .checkClassConsistency(grid.density.obj, field = "class.x", objectName = x) + .checkClassConsistency(grid.density.obj, field = "class.y", objectName = y) } grid.density.obj <- lapply(grid.density.obj, function(r) r$grid) numcol <- dim(grid.density.obj[[1]])[2] # print the number of invalid cells in each participating study for (i in 1:num.sources){ - message(stdnames[i],': ', names(dimnames(grid.density.obj[[i]])[2])) + cli_inform("{.val {stdnames[i]}}: {names(dimnames(grid.density.obj[[i]])[2])}") } return(grid.density.obj) }else{ - stop('Function argument "type" has to be either "combine" or "split"') + .abortInvalidChoice("type", c("combine", "split")) } } diff --git a/R/ds.dim.R b/R/ds.dim.R index efafd5862..d284eb9a2 100644 --- a/R/ds.dim.R +++ b/R/ds.dim.R @@ -80,11 +80,9 @@ #' ds.dim <- function(x=NULL, type='both', datasources=NULL, classConsistencyCheck=TRUE) { - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of a data.frame or matrix!", call.=FALSE) - } + .checkArgProvided(x, "the name of a data.frame or matrix") ################################################################################################### #MODULE: EXTEND "type" argument to include "both" and enable valid aliases # @@ -130,7 +128,7 @@ ds.dim <- function(x=NULL, type='both', datasources=NULL, classConsistencyCheck= out <- c(dimensions, pooled.dim) names(out) <- c(outputnames, paste0('dimensions of ', x, ' in combined studies')) }else{ - stop('Function argument "type" has to be either "both", "combine" or "split"') + .abortInvalidChoice("type", c("both", "combine", "split")) } } } diff --git a/R/ds.dmtC2S.R b/R/ds.dmtC2S.R index 96d059e61..c8a5fa32e 100644 --- a/R/ds.dmtC2S.R +++ b/R/ds.dmtC2S.R @@ -46,17 +46,13 @@ #' ds.dmtC2S <- function(dfdata=NA, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if a value has been provided for dfdata - if(is.null(dfdata)){ - return("Error: dfdata must be a character string, a numeric vector or a scalar") - } + .checkArgProvided(dfdata, "a character string, numeric vector or scalar") # if no value specified for output object, then specify a default - if(is.null(newobj)){ - newobj <- "dmt.copied.C2S" - } + newobj <- .resolveNewobjName(newobj, "dmt.copied.C2S") #Generate values for arguments reflecting the key characteristics of the #clientside matrix/data frame to be copied to the serverside @@ -86,8 +82,8 @@ if(dplyr::is.tbl(dfdata)) if(!is.matrix(dfdata) && !is.data.frame(dfdata) && !dplyr::is.tbl(dfdata)) { - message("\n FAILED: must either be a data.frame, matrix or tibble") - return('Please respecify') + supplied <- .describeSupplied(dfdata) # nolint: object_usage_linter. Used in the cli template + cli_abort("{.arg dfdata} must be a {.cls data.frame}, {.cls matrix}, or {.cls tbl_df}, not {supplied}.") } inout.object.transmit<-paste0(as.character(inout.object),collapse=",") diff --git a/R/ds.elspline.R b/R/ds.elspline.R index 40a77db4d..696c0765a 100644 --- a/R/ds.elspline.R +++ b/R/ds.elspline.R @@ -28,24 +28,18 @@ #' ds.elspline <- function(x, n, marginal = FALSE, names = NULL, newobj = NULL, datasources = NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input variable x!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input variable") - if(is.null(n)){ - stop("Argument 'n' is missing, with no default!", call.=FALSE) - } + .checkArgProvided(n, "a number of knots") if(n < 2){ - stop("'n' must be a value greater than or equal to 2!", call.=FALSE) + cli_abort("{.arg n} must be greater than or equal to 2, not {.val {n}}.") } # create a name by default if user did not provide a name for the new variable - if(is.null(newobj)){ - newobj <- "elspline.newobj" - } + newobj <- .resolveNewobjName(newobj, "elspline.newobj") # now do the business calltext <- call("elsplineDS", x, n, marginal, names) diff --git a/R/ds.exists.R b/R/ds.exists.R index b7a378144..bf395d1b8 100644 --- a/R/ds.exists.R +++ b/R/ds.exists.R @@ -62,11 +62,9 @@ #' ds.exists <- function(x=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input object!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input object") # call the server side function that does the job cally <- call("exists", x) diff --git a/R/ds.exp.R b/R/ds.exp.R index c23fbaba4..19677532e 100644 --- a/R/ds.exp.R +++ b/R/ds.exp.R @@ -58,15 +58,11 @@ #' ds.exp <- function(x=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input object!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input object") - if(is.null(newobj)){ - newobj <- "exp.newobj" - } + newobj <- .resolveNewobjName(newobj, "exp.newobj") cally <- call("expDS", x) DSI::datashield.assign(datasources, newobj, cally) diff --git a/R/ds.forestplot.R b/R/ds.forestplot.R index d71fafdb1..1c2183234 100644 --- a/R/ds.forestplot.R +++ b/R/ds.forestplot.R @@ -59,7 +59,7 @@ ds.forestplot <- function(mod, variable = NULL, method = "ML", layout = "JAMA"){ if(variables[1] == "(Intercept)"){variable <- variables[2]} else {variable <- variables[1]} } else { # Check supplied variable exists if(!(variable %in% variables)){ - stop("[", variable, "] is not valid. Valid variables [", paste(variables, collapse = ", "), "]") + .abortInvalidChoice("variable", variables) } } diff --git a/R/ds.gamlss.R b/R/ds.gamlss.R index 4a0d040ed..bfcb1d021 100644 --- a/R/ds.gamlss.R +++ b/R/ds.gamlss.R @@ -82,12 +82,10 @@ ds.gamlss <- function(formula = NULL, sigma.formula = '~1', nu.formula = '~1', i.control = c(0.001, 50, 30, 0.001), centiles = FALSE, xvar = NULL, newobj = NULL, datasources = NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # verify that 'formula' was set - if(is.null(formula)){ - stop(" Please provide a valid formula!", call.=FALSE) - } + .checkArgProvided(formula, "a valid formula") formula <- gsub("(", "left_parenthesis", formula, fixed = TRUE) formula <- gsub(")", "right_parenthesis", formula, fixed = TRUE) @@ -125,7 +123,7 @@ ds.gamlss <- function(formula = NULL, sigma.formula = '~1', nu.formula = '~1', # check if method is either 'RS', 'CG' or 'mixed if(!(method %in% c("RS", "CG", "mixed"))){ - stop("Argument 'method' must be either 'RS', 'CG' or 'mixed'", call.=FALSE) + .abortInvalidChoice("method", c("RS", "CG", "mixed")) } control <- paste0(as.character(control), collapse=",") @@ -155,12 +153,10 @@ ds.gamlss <- function(formula = NULL, sigma.formula = '~1', nu.formula = '~1', # } if(centiles==TRUE & is.null(xvar)){ - stop("Provide the name of the explanatory variable in 'xvar' argument", call.=FALSE) + cli_abort("{.arg xvar} must name the explanatory variable when {.arg centiles} is {.code TRUE}, not {.code NULL}.") } - if(is.null(newobj)){ - newobj <- 'gamlss_res' - } + newobj <- .resolveNewobjName(newobj, 'gamlss_res') calltext <- call('gamlssDS', formula=formula, sigma.formula=sigma.formula, nu.formula=nu.formula, tau.formula=tau.formula, diff --git a/R/ds.getWGSR.R b/R/ds.getWGSR.R index f7fa79e36..0f6300d58 100644 --- a/R/ds.getWGSR.R +++ b/R/ds.getWGSR.R @@ -103,38 +103,31 @@ #' ds.getWGSR <- function(sex=NULL, firstPart=NULL, secondPart=NULL, index=NULL, standing=NA, thirdPart=NA, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(sex)){ - stop("Please provide the column name of the 'sex' variable!", call.=FALSE) - } + .checkArgProvided(sex, "the name of the sex column") - if(is.null(firstPart)){ - stop("Please provide the column name of the 'firstPart' variable!", call.=FALSE) - } + .checkArgProvided(firstPart, "the name of the column that holds the first part") - if(is.null(secondPart)){ - stop("Please provide the column name of the 'secondPart' variable!", call.=FALSE) - } + .checkArgProvided(secondPart, "the name of the column that holds the second part") if(!any(index %in% c("bfa", "hca", "hfa", "lfa", "mfa", "ssa", "tsa", "wfa", "wfh", "wfl"))){ - stop("Please provide a correct abbreviation for the index!", call.=FALSE) + .abortInvalidChoice("index", c("bfa", "hca", "hfa", "lfa", "mfa", "ssa", "tsa", "wfa", "wfh", "wfl")) } # If 'thirdPart' (age) is missing for BMI-for-age return an error message if(index == "bfa" & is.na(thirdPart)) { - stop("'thirdPart' variable should not be missing for index 'bfa'", call.=FALSE) + cli_abort("{.arg thirdPart} must be provided when {.arg index} is {.val bfa}, not {.code NA}.") } # If 'standing' is not a value either 1, 2, 3, or NA return an error message if(!any(standing %in% c(NA, 1, 2, 3))) { - stop("The 'standing' variable must be a numeric value either 1, 2, or 3!", call.=FALSE) + supplied <- .describeSupplied(standing) # nolint: object_usage_linter. Used in the cli template + cli_abort("{.arg standing} must be {.or {.val {1:3}}}, not {supplied}.") } # check newobj not actively declared as null - if(is.null(newobj)){ - newobj <- "getWGSR.newobj" - } + newobj <- .resolveNewobjName(newobj, "getWGSR.newobj") cally <- call("getWGSRDS", sex, firstPart, secondPart, index, standing, thirdPart) DSI::datashield.assign(datasources, newobj, cally) diff --git a/R/ds.glm.R b/R/ds.glm.R index d69377950..1534de5f1 100644 --- a/R/ds.glm.R +++ b/R/ds.glm.R @@ -322,33 +322,23 @@ ds.glm <- function(formula=NULL, data=NULL, family=NULL, offset=NULL, weights=NULL, checks=FALSE, maxit=20, CI=0.95, viewIter=FALSE, viewVarCov=FALSE, viewCor=FALSE, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # verify that 'formula' was set - if(is.null(formula)){ - stop(" Please provide a valid regression formula!", call.=FALSE) - } + .checkArgProvided(formula, "a valid regression formula") # check if user gave offset or weights directly in formula, if so the argument 'offset' or 'weights' # to provide name of offset or weights variable - if(sum(as.numeric(grepl('offset', formula, ignore.case=TRUE)))>0 || - sum(as.numeric(grepl('weights', formula, ignore.case=TRUE)))>0){ - message("\n\n WARNING: you may have specified an offset or regression weights") - message("\n as part of the model formula. In ds.glm (unlike the usual glm in R)") - message("\n you must specify an offset or weights separately from the formula") - message("\n using the offset or weights argument.\n\n") - } + .checkOffsetInFormula(formula) formula <- stats::as.formula(formula) # check that 'family' was set - if(is.null(family)){ - stop(" Please provide a valid 'family' argument!", call.=FALSE) - } + .checkArgProvided(family, "a valid family") # beginning of optional checks - the process stops if any of these checks fails # if(checks){ - message(" -- Verifying the variables in the model") + cli_inform("Verifying the variables in the model.") # call the function that checks the variables in the formula are defined (exist) on the server site and are not missing at complete glmChecks(formula, data, offset, weights, datasources) }else{ @@ -426,36 +416,17 @@ ds.glm <- function(formula=NULL, data=NULL, family=NULL, offset=NULL, weights=NU errorMessage <- as.matrix(errorMessage) dimnames(errorMessage) <- list(names(datasources), "ERROR MESSAGES") - output.blocked.information.1 <- "MODEL FITTING TERMINATED AT FIRST ITERATION:" - output.blocked.information.2 <- "Any values of 1 in the following tables denote potential disclosure risks" - output.blocked.information.3 <- "please use the argument to include only valid studies." - output.blocked.information.4 <- "Errors by study are as follows:" if(sum.y.invalid>0||sum.Xpar.invalid>0||sum.w.invalid>0||sum.o.invalid>0||sum.glm.saturation.invalid>0||at.least.one.study.data.error==1){ - message("\n\nMODEL FITTING TERMINATED AT FIRST ITERATION:\n", - "Any values of 1 in the following tables denote potential disclosure risks\n", - "please use the argument to include only valid studies.\n", - "Errors by study are as follows:\n") - message(as.matrix(y.invalid)) - message(as.matrix(Xpar.invalid)) - message(as.matrix(w.invalid)) - message(as.matrix(o.invalid)) - message(as.matrix(glm.saturation.invalid)) - message(as.matrix(errorMessage)) - - return(list( - output.blocked.information.1, - output.blocked.information.2, - output.blocked.information.3, - output.blocked.information.4, - y.vector.error=y.invalid, - X.matrix.error=Xpar.invalid, - weight.vector.error=w.invalid, - offset.vector.error=o.invalid, - glm.overparameterized=glm.saturation.invalid, - errorMessage=errorMessage - )) - stop("DATA ERROR") + cli_inform(c("Model fitting terminated at the first iteration.", "i" = "Values of 1 in the following tables denote potential disclosure risks.", "*" = "Use {.arg datasources} to include only valid studies.")) + cli_verbatim(utils::capture.output(as.matrix(y.invalid))) + cli_verbatim(utils::capture.output(as.matrix(Xpar.invalid))) + cli_verbatim(utils::capture.output(as.matrix(w.invalid))) + cli_verbatim(utils::capture.output(as.matrix(o.invalid))) + cli_verbatim(utils::capture.output(as.matrix(glm.saturation.invalid))) + cli_verbatim(utils::capture.output(as.matrix(errorMessage))) + + cli_abort("Can't fit the model because of a data error.") } beta.vect.next <- rep(0, num.par.glm) @@ -478,7 +449,7 @@ ds.glm <- function(formula=NULL, data=NULL, family=NULL, offset=NULL, weights=NU iteration.count<-iteration.count+1 - message("Iteration ", iteration.count, "...") + cli_inform("Iteration {iteration.count}...") # NOW CALL SECOND COMPONENT OF glmDS TO GENERATE SCORE VECTORS AND INFORMATION MATRICES cally2 <- call('glmDS2', formula, family, beta.vect.temp, offset, weights, data) @@ -506,34 +477,9 @@ ds.glm <- function(formula=NULL, data=NULL, family=NULL, offset=NULL, weights=NU dimnames(errorMessage2) <- list(names(datasources), "ERROR MESSAGES") if(disclosure.risk.total>0){ - message("Potential disclosure risk in y.vect, X.mat, w.vect or offset \n", - "or model overparameterized in at least one study.\n", - "In addition clientside function appears to have been modified\n", - "to avoid traps in first serverside function.\n", - "Score vectors and information matrices therefore destroyed in all invalid studies\n", - "and model fitting terminated. This error is recorded in the log file but\n", - "please report it to the DataSHIELD team as we need to understand how\n", - "the controlled shutdown traps in glmDS1 have been circumvented\n\n") - - output.blocked.information.1<-"Potential disclosure risk in y.vect, X.mat, w.vect or offset" - output.blocked.information.2<-"or model overparameterized in at least one study." - output.blocked.information.3<-"In addition clientside function appears to have been modified" - output.blocked.information.4<-"to avoid disclosure traps in first serverside function." - output.blocked.information.5<-"Score vectors and information matrices therefore destroyed in all invalid studies" - output.blocked.information.6<-"and model fitting terminated. This error is recorded in the log file but" - output.blocked.information.7<-"please also report it to the DataSHIELD team as we need to understand how" - output.blocked.information.8<-"the controlled shutdown traps in glmDS1 have been circumvented." - - - return(list(output.blocked.information.1, - output.blocked.information.2, - output.blocked.information.3, - output.blocked.information.4, - output.blocked.information.5, - output.blocked.information.6, - output.blocked.information.7, - output.blocked.information.8 - )) + cli_inform(c("Potential disclosure risk in y.vect, X.mat, w.vect or offset, or the model is overparameterized, in at least one study.", "x" = "The client-side function also appears to have been modified to avoid traps in the first server-side function.", "i" = "Score vectors and information matrices were destroyed in all invalid studies and model fitting was terminated.", "*" = "This error is recorded in the log file. Please report it to the DataSHIELD team, as we need to understand how the controlled shutdown traps in {.fn glmDS1} were circumvented.")) + + cli_abort("Can't fit the model because of a potential disclosure risk.") } @@ -544,7 +490,7 @@ ds.glm <- function(formula=NULL, data=NULL, family=NULL, offset=NULL, weights=NU Nmissing.total<-Reduce(f="+", .select(study.summary, 'Nmissing')) Ntotal.total<-Reduce(f="+", .select(study.summary, 'Ntotal')) - message("CURRENT DEVIANCE: ", dev.total) + cli_inform("Current deviance: {dev.total}.") if(iteration.count==1) { # Sum participants only during first iteration. @@ -582,36 +528,36 @@ ds.glm <- function(formula=NULL, data=NULL, family=NULL, offset=NULL, weights=NU if(viewIter){ #For ALL iterations summarise model state after current iteration - message("SUMMARY OF MODEL STATE after iteration ", iteration.count) - message("Current deviance ", dev.total," on ",(nsubs.total-length(beta.vect.next)), " degrees of freedom") - message("Convergence criterion ",converge.state," (", converge.value,")") + cli_inform("Summary of model state after iteration {iteration.count}.") + cli_inform("Current deviance {dev.total} on {nsubs.total-length(beta.vect.next)} degrees of freedom.") + cli_inform("Convergence criterion {converge.state} ({converge.value}).") - message("\nbeta: ", paste(as.vector(beta.vect.next), collapse=" ")) + cli_inform("beta: {paste(as.vector(beta.vect.next), collapse = ' ')}") - message("\nInformation matrix overall:") - message(paste(utils::capture.output(info.matrix.total), collapse="\n")) + cli_inform("Information matrix overall:") + cli_verbatim(utils::capture.output(info.matrix.total)) - message("\nScore vector overall:") - message(paste(utils::capture.output(score.vect.total), collapse="\n")) + cli_inform("Score vector overall:") + cli_verbatim(utils::capture.output(score.vect.total)) - message("\nCurrent deviance: ", dev.total, "\n") + cli_inform("Current deviance: {dev.total}.") } } if(!viewIter){ #For ALL iterations summarise model state after current iteration - message("SUMMARY OF MODEL STATE after iteration ", iteration.count) - message("Current deviance ", dev.total," on ",(nsubs.total-length(beta.vect.next)), " degrees of freedom") - message("Convergence criterion ",converge.state," (", converge.value,")") + cli_inform("Summary of model state after iteration {iteration.count}.") + cli_inform("Current deviance {dev.total} on {nsubs.total-length(beta.vect.next)} degrees of freedom.") + cli_inform("Convergence criterion {converge.state} ({converge.value}).") - message("\nbeta: ", paste(as.vector(beta.vect.next), collapse=" ")) + cli_inform("beta: {paste(as.vector(beta.vect.next), collapse = ' ')}") - message("\nInformation matrix overall:") - message(paste(utils::capture.output(info.matrix.total), collapse="\n")) + cli_inform("Information matrix overall:") + cli_verbatim(utils::capture.output(info.matrix.total)) - message("\nScore vector overall:") - message(paste(utils::capture.output(score.vect.total), collapse="\n")) + cli_inform("Score vector overall:") + cli_verbatim(utils::capture.output(score.vect.total)) - message("\nCurrent deviance: ", dev.total, "\n") + cli_inform("Current deviance: {dev.total}.") } #If convergence has been obtained, declare final (maximum likelihood) beta vector, @@ -806,7 +752,7 @@ ds.glm <- function(formula=NULL, data=NULL, family=NULL, offset=NULL, weights=NU } } else { - warning(paste("Did not converge after", maxit, "iterations. Increase maxit parameter as necessary.")) + cli_warn(c("The model didn't converge after {maxit} iterations.", "i" = "Increase {.arg maxit} if necessary.")) return(NULL) } diff --git a/R/ds.glmPredict.R b/R/ds.glmPredict.R index e7e0c02ac..e967d1e36 100644 --- a/R/ds.glmPredict.R +++ b/R/ds.glmPredict.R @@ -128,27 +128,23 @@ ds.glmPredict <- function(glmname = NULL, newdataname = NULL, output.type = "res se.fit = FALSE, dispersion = NULL, terms = NULL, na.action = "na.pass", newobj = NULL, datasources = NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check that is set - if(is.null(glmname)){ - stop(" is not set, please specify it as a character string containing the name of a valid glm class object on the serverside", call.=FALSE) - } + .checkArgProvided(glmname, "the name of a glm object on the server") # check that is correctly set if((output.type!="link") && (output.type!="response") && (output.type!="terms")){ - stop(" is not correctly set, please specify it as one of three character strings: 'link', 'response', or 'terms'", call.=FALSE) + .abortInvalidChoice("output.type", c("link", "response", "terms")) } # check that is correctly set if((na.action!="na.fail")&&(na.action!="na.omit")&&(na.action!="na.exclude")&&(na.action!="na.pass")){ - stop(" is not correctly set, please specify it as one of four character strings: 'na.fail', 'na.omit', 'na.exclude' or 'na.pass'", call.=FALSE) + .abortInvalidChoice("na.action", c("na.fail", "na.omit", "na.exclude", "na.pass")) } # provide value for newobj if none specified - if(is.null(newobj)){ - newobj<-"predict_glm" - } + newobj <- .resolveNewobjName(newobj, "predict_glm") calltext <- call("glmPredictDS.as", glmname, newdataname, output.type, se.fit, dispersion, terms, na.action) DSI::datashield.assign(datasources, newobj, calltext) diff --git a/R/ds.glmSLMA.R b/R/ds.glmSLMA.R index b86271248..19f3515a7 100644 --- a/R/ds.glmSLMA.R +++ b/R/ds.glmSLMA.R @@ -370,31 +370,20 @@ ds.glmSLMA<-function(formula=NULL, family=NULL, offset=NULL, weights=NULL, combine.with.metafor=TRUE, newobj=NULL,dataName=NULL,checks=FALSE, maxit=30, notify.of.progress=FALSE, datasources=NULL) { - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # verify that 'formula' was set - if(is.null(formula)){ - stop(" Please provide a valid regression formula!", call.=FALSE) - } + .checkArgProvided(formula, "a valid regression formula") # check if user gave offset or weights directly in formula, if so the argument 'offset' or 'weights' # to provide name of offset or weights variable - if(sum(as.numeric(grepl('offset', formula, ignore.case=TRUE)))>0 || - sum(as.numeric(grepl('weights', formula, ignore.case=TRUE)))>0) -{ - message("\n\n WARNING: you may have specified an offset or regression weights") - message("\n as part of the model formula. In ds.glm (unlike the usual glm in R)") - message("\n you must specify an offset or weights separately from the formula") - message("\n using the offset or weights argument.\n\n") -} + .checkOffsetInFormula(formula) formula <- stats::as.formula(formula) # check that 'family' was set - if(is.null(family)){ - stop(" Please provide a valid 'family' argument!", call.=FALSE) - } + .checkArgProvided(family, "a valid family") ##################### #if family is non-standard (i.e.family includes calls to either link or variance) convert to transmittable form: @@ -440,7 +429,7 @@ ds.glmSLMA<-function(formula=NULL, family=NULL, offset=NULL, weights=NULL, combi # beginning of optional checks - the process stops if any of these checks fails # if(checks){ - message(" -- Verifying the variables in the model") + cli_inform("Verifying the variables in the model.") # call the function that checks the variables in the formula are defined (exist) on the server site and are not missing at complete glmChecks(formula, dataName, offset, weights, datasources) @@ -531,43 +520,26 @@ dimnames(errorMessage)<-list(names(datasources),"ERROR MESSAGES") -output.blocked.information.1<-"EVERY STUDY HAS DATA THAT COULD BE POTENTIALLY DISCLOSIVE UNDER THE CURRENT MODEL:" -output.blocked.information.2<-"Any values of 1 in the following tables denote potential disclosure risks." -output.blocked.information.3<-"Please use the argument to include only valid studies." -output.blocked.information.4<-"Errors by study are as follows:" #CASE 1 - NO STUDIES VALID if(!at.least.one.study.valid) { - message("\n\nEVERY STUDY HAS DATA THAT COULD BE POTENTIALLY DISCLOSIVE UNDER THE CURRENT MODEL:\n", - "Any values of 1 in the following tables denote potential disclosure risks.\n", - "Errors by study are as follows:\n") - - - return(list( - output.blocked.information.1, - output.blocked.information.2, - output.blocked.information.4, - y.vector.error=y.invalid, - X.matrix.error=Xpar.invalid, - weight.vector.error=w.invalid, - offset.vector.error=o.invalid, - glm.overparameterized=glm.saturation.invalid, - errorMessage=errorMessage - )) + cli_inform(c("Every study has data that could be potentially disclosive under the current model.", "i" = "Values of 1 in the following tables denote potential disclosure risks.")) + + cli_verbatim(utils::capture.output(as.matrix(y.invalid))) + cli_verbatim(utils::capture.output(as.matrix(Xpar.invalid))) + cli_verbatim(utils::capture.output(as.matrix(w.invalid))) + cli_verbatim(utils::capture.output(as.matrix(o.invalid))) + cli_verbatim(utils::capture.output(as.matrix(glm.saturation.invalid))) + cli_verbatim(utils::capture.output(as.matrix(errorMessage))) + cli_abort("Can't fit the model because every study has data that could be disclosive.") } #CASE 2 - AT LEAST ONE STUDY VALID AND AT LEAST ONE INVALID if(at.least.one.study.data.error) { - message("\n\nAT LEAST ONE STUDY HAS DATA THAT COULD BE POTENTIALLY DISCLOSIVE UNDER THE CURRENT MODEL:\n", - "Any values of 1 in the following tables denote potential disclosure risks.\n", - "No analytic results are returned for potentially disclosive studies and\n", - "pooled co-estimates across studies are based only on the valid studies.\n", - "You may also choose to exclude invalid studies from\n", - "the whole analysis using the argument.\n", - "Errors by study are as follows:\n") + cli_inform(c("At least one study has data that could be potentially disclosive under the current model.", "i" = "Values of 1 in the following tables denote potential disclosure risks.", "*" = "No results are returned for those studies, and pooled estimates use only the valid studies. You can exclude invalid studies from the whole analysis with {.arg datasources}.")) } beta.vect.next <- rep(0,num.par.glm) @@ -591,12 +563,10 @@ if(at.least.one.study.data.error) #OBJECT ON SERVERSIDE # if no value specified for glm output object, then specify a default - if(is.null(newobj)){ - newobj <- "new.glm.obj" - } + newobj <- .resolveNewobjName(newobj, "new.glm.obj") if (notify.of.progress) { - message("\n\nSAVING SERVERSIDE glm OBJECT AS: <",newobj,">\n\n") + cli_inform("Saving server-side glm object as {.val {newobj}}.") } calltext.2 <- call('glmSLMADS.assign', formula, family, offset, weights, dataName) @@ -643,17 +613,16 @@ if(!all.studies.valid) { for(sse in study.with.errors) { - message("\n","Error report from second serverside function for study",sse,"\n") - message("############################################################","\n") - message(unlist(study.summary[[sse]][[1]]),"\n") - message(unlist(study.summary[[sse]][[2]]),"\n\n") + cli_inform("Error report from second server-side function for {.val {names(datasources)[sse]}}.") + cli_verbatim(unlist(study.summary[[sse]][[1]])) + cli_verbatim(unlist(study.summary[[sse]][[2]])) num.messages<-length(study.summary[[sse]])-2 for(m in 1:num.messages) { if(!is.null(unlist(study.summary[[sse]][[2+m]]))) { - message(unlist(study.summary[[sse]][[2+m]]),"\n\n") + cli_verbatim(as.character(unlist(study.summary[[sse]][[2+m]]))) } } } @@ -785,8 +754,7 @@ if(num.valid.studies>1){ if(!coefficient.vectors.match){ - message("\n\nModels in different sources vary in structure\nplease match coefficients for meta-analysis individually\n") - message("nYou can use the DataSHIELD generated estimates and standard errors as the basis for a meta-analysis\nbut carry out the final pooling step independently of DataSHIELD using whatever meta-analysis package you wish\n\n") + cli_inform(c("Models in different sources vary in structure.", "i" = "Match coefficients for meta-analysis individually.", "*" = "You can use the DataSHIELD estimates and standard errors as the basis for a meta-analysis, but carry out the final pooling step independently of DataSHIELD.")) return(list(output.summary=output.summary)) } diff --git a/R/ds.glmSummary.R b/R/ds.glmSummary.R index 077475847..7e57cedcb 100644 --- a/R/ds.glmSummary.R +++ b/R/ds.glmSummary.R @@ -79,17 +79,16 @@ #' ds.glmSummary <- function(x.name, newobj=NULL, datasources=NULL) { - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if a value has been provided for x if(is.null(x.name)||!is.character(x.name)){ - stop("Error: x.name must denote a character string naming the glm object on the serverside to be summarised", call.=FALSE) + supplied <- .describeSupplied(x.name) # nolint: object_usage_linter. Used in the cli template + cli_abort("{.arg x.name} must be a character string that names a glm object on the server, not {supplied}.") } # create a name by default if the user did not provide a name for the new object - if (is.null(newobj)) { - newobj <- "summary_glm.newobj" - } + newobj <- .resolveNewobjName(newobj, "summary_glm.newobj") # PREPARE AND CALL THE ASSIGN FUNCTION TO PREPARE THE summary_glm OBJECT ON THE SERVERSIDE calltext1 <- call("glmSummaryDS.as", x.name) diff --git a/R/ds.glmerSLMA.R b/R/ds.glmerSLMA.R index ed254a081..455c105f5 100644 --- a/R/ds.glmerSLMA.R +++ b/R/ds.glmerSLMA.R @@ -247,34 +247,23 @@ ds.glmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.m start_theta = NULL, start_fixef = NULL, notify.of.progress=FALSE, assign=FALSE, newobj=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # verify that 'formula' was set - if(is.null(formula)){ - stop(" Please provide a valid regression formula!", call.=FALSE) - } + .checkArgProvided(formula, "a valid regression formula") # check if user gave offset or weights directly in formula, if so the argument 'offset' or 'weights' # to provide name of offset or weights variable - if(sum(as.numeric(grepl('offset', formula, ignore.case=TRUE)))>0 || - sum(as.numeric(grepl('weights', formula, ignore.case=TRUE)))>0) - { - message("\n\n WARNING: you may have specified an offset or regression weights") - message("\n as part of the model formula. In ds.glm (unlike the usual glm in R)") - message("\n you must specify an offset or weights separately from the formula") - message("\n using the offset or weights argument.\n\n") - } + .checkOffsetInFormula(formula) formula <- stats::as.formula(formula) # check that 'family' was set - if(is.null(family)){ - stop(" Please provide a valid 'family' argument!", call.=FALSE) - } + .checkArgProvided(family, "a valid family") # beginning of optional checks - the process stops if any of these checks fails # if(checks){ - message(" -- Verifying the variables in the model") + cli_inform("Verifying the variables in the model.") # call the function that checks the variables in the formula are defined (exist) on the server site and are not missing at complete glmChecks(formula, dataName, offset, weights, datasources) @@ -311,9 +300,7 @@ ds.glmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.m if(!is.null(control_type) && is.null(control_value)) { - errorMessage.cv<-"ERROR: if control_type is non-null, you must specify a valid control_value eg control_value<-1.0e-7" - # print(errorMessage.cv) - return(list(errorMessage=errorMessage.cv)) + cli_abort(c("{.arg control_value} must be set when {.arg control_type} is set, not {.code NULL}.", "i" = "For example, {.code control_value = 1.0e-7}.")) } if(!is.null(control_value)) @@ -342,13 +329,11 @@ ds.glmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.m if(assign==TRUE){ - if(is.null(newobj)){ - newobj <- "new.glmer.obj" - } + newobj <- .resolveNewobjName(newobj, "new.glmer.obj") if (notify.of.progress) { - message("\n\nSAVING SERVERSIDE glmerMod OBJECT AS: <",newobj,">\n\n") + cli_inform("Saving server-side glmerMod object as {.val {newobj}}.") } calltext.2 <- call('glmerSLMADS.assign', formula, offset, weights, dataName, family, @@ -392,17 +377,16 @@ ds.glmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.m { for(sse in study.with.errors) { - message("\n","Error report from second serverside function for study",sse,"\n") - message("############################################################","\n") - message(unlist(study.summary[[sse]][[1]]),"\n") - message(unlist(study.summary[[sse]][[2]]),"\n\n") + cli_inform("Error report from second server-side function for {.val {names(datasources)[sse]}}.") + cli_verbatim(unlist(study.summary[[sse]][[1]])) + cli_verbatim(unlist(study.summary[[sse]][[2]])) num.messages<-length(study.summary[[sse]])-2 for(m in 1:num.messages) { if(!is.null(unlist(study.summary[[sse]][[2+m]]))) { - message(unlist(study.summary[[sse]][[2+m]]),"\n\n") + cli_verbatim(as.character(unlist(study.summary[[sse]][[2+m]]))) } } } @@ -410,8 +394,7 @@ ds.glmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.m if(all.studies.valid) { - message("\nAll studies passed disclosure tests\n") - message("Please check for convergence warnings in the study summaries\n\n\n") + cli_inform(c("All studies passed disclosure tests.", "i" = "Check for convergence warnings in the study summaries.")) } } @@ -536,8 +519,7 @@ ds.glmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.m if(!coefficient.vectors.match){ - message("\n\nModels in different sources vary in structure\nplease match coefficients for meta-analysis individually\n") - message("nYou can use the DataSHIELD generated estimates and standard errors as the basis for a meta-analysis\nbut carry out the final pooling step independently of DataSHIELD using whatever meta-analysis package you wish\n\n") + cli_inform(c("Models in different sources vary in structure.", "i" = "Match coefficients for meta-analysis individually.", "*" = "You can use the DataSHIELD estimates and standard errors as the basis for a meta-analysis, but carry out the final pooling step independently of DataSHIELD.")) return(list(output.summary=output.summary)) } @@ -600,10 +582,10 @@ ds.glmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.m if (notify.of.progress) { - message("Convergence information\n") + cli_inform("Convergence information:") for(r in 1:numstudies) { - message(full.error.message[r],"\n") + cli_inform("{full.error.message[r]}") } } diff --git a/R/ds.heatmapPlot.R b/R/ds.heatmapPlot.R index 33d402aa4..804fc941e 100644 --- a/R/ds.heatmapPlot.R +++ b/R/ds.heatmapPlot.R @@ -153,15 +153,11 @@ ds.heatmapPlot <- function(x=NULL, y=NULL, type="combine", show="all", numints=20, method="smallCellsRule", k=3, noise=0.25, datasources=NULL, classConsistencyCheck=FALSE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("x=NULL. Please provide the names of the 1st numeric vector!", call.=FALSE) - } + .checkArgProvided(x, "the name of the first numeric vector") - if(is.null(y)){ - stop("y=NULL. Please provide the names of the 2nd numeric vector!", call.=FALSE) - } + .checkArgProvided(y, "the name of the second numeric vector") # Save par and setup reseting of par values old_par <- graphics::par(no.readonly = TRUE) @@ -169,7 +165,7 @@ ds.heatmapPlot <- function(x=NULL, y=NULL, type="combine", show="all", numints=2 # the argument method must be either "smallCellsRule" or "deterministic" or "probabilistic" if(method != 'smallCellsRule' & method != 'deterministic' & method != 'probabilistic'){ - stop('Function argument "method" has to be either "smallCellsRule" or "deterministic" or "probabilistic"', call.=FALSE) + .abortInvalidChoice("method", c("smallCellsRule", "deterministic", "probabilistic")) } # prepare the axis labels @@ -193,8 +189,8 @@ ds.heatmapPlot <- function(x=NULL, y=NULL, type="combine", show="all", numints=2 # call the server-side function that generates the x and y coordinates of the centroids anonymous.data <- datashield.aggregate(datasources, call("heatmapPlotDS", x.name=x, y.name=y, k=k, noise=noise, method.indicator=method.indicator)) if(classConsistencyCheck){ - .checkClassConsistency(anonymous.data, field = "class.x", object_name = x) - .checkClassConsistency(anonymous.data, field = "class.y", object_name = y) + .checkClassConsistency(anonymous.data, field = "class.x", objectName = x) + .checkClassConsistency(anonymous.data, field = "class.y", objectName = y) } pooled.points.x <- c() @@ -212,8 +208,8 @@ ds.heatmapPlot <- function(x=NULL, y=NULL, type="combine", show="all", numints=2 # call the server-side function that generates the x and y coordinates of the anonymous.data anonymous.data <- datashield.aggregate(datasources, call("heatmapPlotDS", x.name=x, y.name=y, k=k, noise=noise, method.indicator=method.indicator)) if(classConsistencyCheck){ - .checkClassConsistency(anonymous.data, field = "class.x", object_name = x) - .checkClassConsistency(anonymous.data, field = "class.y", object_name = y) + .checkClassConsistency(anonymous.data, field = "class.x", objectName = x) + .checkClassConsistency(anonymous.data, field = "class.y", objectName = y) } pooled.points.x <- c() @@ -254,8 +250,8 @@ ds.heatmapPlot <- function(x=NULL, y=NULL, type="combine", show="all", numints=2 # generate the grid density object to plot grid.density.obj <- datashield.aggregate(datasources, call("densityGridDS", x=x, y=y, limits=TRUE, x.min=x.global.min, x.max=x.global.max, y.min=y.global.min, y.max=y.global.max, numints=numints)) if(classConsistencyCheck){ - .checkClassConsistency(grid.density.obj, field = "class.x", object_name = x) - .checkClassConsistency(grid.density.obj, field = "class.y", object_name = y) + .checkClassConsistency(grid.density.obj, field = "class.x", objectName = x) + .checkClassConsistency(grid.density.obj, field = "class.y", objectName = y) } grid.density.obj <- lapply(grid.density.obj, function(r) r$grid) @@ -263,7 +259,7 @@ ds.heatmapPlot <- function(x=NULL, y=NULL, type="combine", show="all", numints=2 # print the number of invalid cells in each participating study for (i in 1:num.sources){ - message(stdnames[i],': ', names(dimnames(grid.density.obj[[i]])[2])) + cli_inform("{.val {stdnames[i]}}: {names(dimnames(grid.density.obj[[i]])[2])}") } Global.grid.density <- matrix(0, dim(grid.density.obj[[1]])[1], numcol-2) @@ -404,7 +400,7 @@ ds.heatmapPlot <- function(x=NULL, y=NULL, type="combine", show="all", numints=2 fields::image.plot(x.zoomed, y.zoomed, z.zoomed, xlab=x.lab, ylab=y.lab, main="Heatmap Plot of the Pooled Data (zoomed)") }else{ - stop('Function argument "show" has to be either "all" or "zoomed"') + .abortInvalidChoice("show", c("all", "zoomed")) } } else if (type=='split') { @@ -413,8 +409,8 @@ ds.heatmapPlot <- function(x=NULL, y=NULL, type="combine", show="all", numints=2 # generate the grid density object to plot grid.density.obj <- datashield.aggregate(datasources, call("densityGridDS", x=x, y=y, limits=FALSE, x.min=NULL, x.max=NULL, y.min=NULL, y.max=NULL, numints=numints)) if(classConsistencyCheck){ - .checkClassConsistency(grid.density.obj, field = "class.x", object_name = x) - .checkClassConsistency(grid.density.obj, field = "class.y", object_name = y) + .checkClassConsistency(grid.density.obj, field = "class.x", objectName = x) + .checkClassConsistency(grid.density.obj, field = "class.y", objectName = y) } grid.density.obj <- lapply(grid.density.obj, function(r) r$grid) @@ -462,7 +458,7 @@ ds.heatmapPlot <- function(x=NULL, y=NULL, type="combine", show="all", numints=2 # print the number of invalid cells in each participating study for (i in 1:num.sources) { - message(stdnames[i],': ', names(dimnames(grid.density.obj[[i]])[2])) + cli_inform("{.val {stdnames[i]}}: {names(dimnames(grid.density.obj[[i]])[2])}") } if(num.sources > 1){ @@ -557,7 +553,7 @@ ds.heatmapPlot <- function(x=NULL, y=NULL, type="combine", show="all", numints=2 fields::image.plot(x.zoomed, y.zoomed, z.zoomed, xlab = x.lab, ylab = y.lab, main = title) }else{ - stop('Function argument "show" has to be either "all" or "zoomed"') + .abortInvalidChoice("show", c("all", "zoomed")) } } @@ -651,11 +647,11 @@ ds.heatmapPlot <- function(x=NULL, y=NULL, type="combine", show="all", numints=2 fields::image.plot(x.zoomed, y.zoomed, z.zoomed, xlab = x.lab, ylab = y.lab, main = "Heatmap Plot of the Pooled Data") }else{ - stop('Function argument "show" has to be either "all" or "zoomed"') + .abortInvalidChoice("show", c("all", "zoomed")) } } }else{ - stop('Function argument "type" has to be either "combine" or "split"') + .abortInvalidChoice("type", c("combine", "split")) } } diff --git a/R/ds.hetcor.R b/R/ds.hetcor.R index 0a47676a3..5fa2da67f 100644 --- a/R/ds.hetcor.R +++ b/R/ds.hetcor.R @@ -32,11 +32,9 @@ #' ds.hetcor <- function(data=NULL, ML=TRUE, std.err=TRUE, bins=4, pd=TRUE, use="complete.obs", datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(data)){ - stop("Please provide the name of the input object!", call.=FALSE) - } + .checkArgProvided(data, "the name of the input object") calltext <- call('hetcorDS', data, ML, std.err, bins, pd, use) output <- DSI::datashield.aggregate(datasources, calltext) diff --git a/R/ds.histogram.R b/R/ds.histogram.R index d0f4a7f31..9d4895f11 100644 --- a/R/ds.histogram.R +++ b/R/ds.histogram.R @@ -155,11 +155,9 @@ #' ds.histogram <- function(x=NULL, type="split", num.breaks=10, method="smallCellsRule", k=3, noise=0.25, vertical.axis="Frequency", datasources=NULL, classConsistencyCheck=FALSE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input vector") # Save par and setup reseting of par values old_par <- graphics::par(no.readonly = TRUE) @@ -167,12 +165,12 @@ ds.histogram <- function(x=NULL, type="split", num.breaks=10, method="smallCells # the argument vertical.axis must be "Frequency" or "Density" if(vertical.axis != 'Frequency' & vertical.axis != 'Density'){ - stop('Function argument "vertical.axis" has to be either "Frequency" or "Density"', call.=FALSE) + .abortInvalidChoice("vertical.axis", c("Frequency", "Density")) } # the argument method must be either "smallCellsRule" or "deterministic" or "probabilistic" if(method != 'smallCellsRule' & method != 'deterministic' & method != 'probabilistic'){ - stop('Function argument "method" has to be either "smallCellsRule" or "deterministic" or "probabilistic"', call.=FALSE) + .abortInvalidChoice("method", c("smallCellsRule", "deterministic", "probabilistic")) } # name of the studies to be used in the plots' titles @@ -188,7 +186,7 @@ ds.histogram <- function(x=NULL, type="split", num.breaks=10, method="smallCells # call the server-side function that returns the range of the vector from each study histogram.ranges <- datashield.aggregate(datasources, call("histogramDS1", x=x, method.indicator=method.indicator, k=k, noise=noise)) if(classConsistencyCheck){ - .checkClassConsistency(histogram.ranges, object_name = x) + .checkClassConsistency(histogram.ranges, objectName = x) } ranges <- unique(unlist(lapply(histogram.ranges, function(r) r$range))) @@ -210,7 +208,7 @@ ds.histogram <- function(x=NULL, type="split", num.breaks=10, method="smallCells for(i in 1:length(datasources)){ output <- outputs[[i]] if(is.null(output)){ - stop("Equidistant break points that span all the data points could not be find, in stdnames[i]!") + cli_abort("Can't find equidistant break points that span all the data in {.val {names(datasources)[i]}}.") } hist.objs[[i]] <- output$histobject invalidcells[[i]] <- output$invalidcells @@ -256,7 +254,9 @@ ds.histogram <- function(x=NULL, type="split", num.breaks=10, method="smallCells numc <- 2 graphics::par(mfrow=c(numr,numc)) for(i in 1:ll){ - warning(names(datasources)[i], ": ", invalidcells[[i]], " invalid cells", immediate.=TRUE, call.=FALSE) + if (invalidcells[[i]] > 0) { + cli_warn("In {.val {names(datasources)[i]}}, {invalidcells[[i]]} bin{?s} had fewer than {.code nfilter.tab} observations, so {?its count was/their counts were} set to 0.") + } if(vertical.axis=="Frequency"){ graphics::plot(hist.objs[[i]], freq=TRUE, xlab=varname, main=paste("Histogram of ", names(datasources)[i], sep="")) } @@ -267,7 +267,9 @@ ds.histogram <- function(x=NULL, type="split", num.breaks=10, method="smallCells return(hist.objs) }else{ graphics::par(mfrow=c(1,1)) - warning(names(datasources)[1], ": ", invalidcells[[1]], " invalid cells", immediate.=TRUE, call.=FALSE) + if (invalidcells[[1]] > 0) { + cli_warn("In {.val {names(datasources)[1]}}, {invalidcells[[1]]} bin{?s} had fewer than {.code nfilter.tab} observations, so {?its count was/their counts were} set to 0.") + } if(vertical.axis=="Frequency"){ graphics::plot(hist.objs[[1]], freq=TRUE, xlab=varname, main=paste("Histogram of ", names(datasources)[1], sep="")) } @@ -277,7 +279,7 @@ ds.histogram <- function(x=NULL, type="split", num.breaks=10, method="smallCells return(hist.objs[[1]]) } }else{ - stop('Function argument "type" has to be either "combine" or "split"') + .abortInvalidChoice("type", c("combine", "split")) } } diff --git a/R/ds.igb_standards.R b/R/ds.igb_standards.R index dd4023045..4819a245f 100644 --- a/R/ds.igb_standards.R +++ b/R/ds.igb_standards.R @@ -42,37 +42,29 @@ ds.igb_standards <- function(gagebrth=NULL, z=0, p=50, val=NULL, var=NULL, sex=NULL, fun='igb_value2zscore', newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if user has provided the name of the input variables - if(is.null(gagebrth)){ - stop("Please provide the name of the gagebrth variable", call.=FALSE) - } - if(is.null(sex)){ - stop("Please provide the name of the sex variable", call.=FALSE) - } + .checkArgProvided(gagebrth, "the name of the gestational age variable") + .checkArgProvided(sex, "the name of the sex variable") # check if the provided fun is valid if(!(fun %in% c("igb_centile2value","igb_zscore2value","igb_value2zscore","igb_value2centile"))){ - stop("Please provide a valid fun", call.=FALSE) + .abortInvalidChoice("fun", c("igb_centile2value", "igb_zscore2value", "igb_value2zscore", "igb_value2centile")) } # check if val is provided if fun is either igb_value2zscore or igb_value2centile if(fun %in% c("igb_value2zscore","igb_value2centile")){ - if(is.null(val)){ - stop("Please provide the name of the val variable", call.=FALSE) - } + .checkArgProvided(val, "the name of the value variable") } # check if the provided var is valid if(!(var %in% c("lencm", "wtkg", "hcircm", "wlr"))){ - stop("Please provide a valid var", call.=FALSE) + .abortInvalidChoice("var", c("lencm", "wtkg", "hcircm", "wlr")) } # if no output variable specified then provide a default name - if(is.null(newobj)){ - newobj <- "igb.newobj" - } + newobj <- .resolveNewobjName(newobj, "igb.newobj") # call the server-side assign function cally <- call('igb_standardsDS', gagebrth, z, p, val, var, sex, fun) diff --git a/R/ds.isNA.R b/R/ds.isNA.R index 63ef26586..5083485e8 100644 --- a/R/ds.isNA.R +++ b/R/ds.isNA.R @@ -59,11 +59,9 @@ #' ds.isNA <- function(x=NULL, datasources=NULL, classConsistencyCheck=TRUE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input vector") stdnames <- names(datasources) xnames <- extract(x) @@ -81,7 +79,7 @@ ds.isNA <- function(x=NULL, datasources=NULL, classConsistencyCheck=TRUE){ for(i in 1:length(results)){ if(results[[i]]$is.na){ track[[i]] <- TRUE - message("The variable ", varname, " in ", stdnames[i], " is missing at complete (all values are 'NA').") + cli_inform("{.val {varname}} has only missing values in {.val {stdnames[i]}}.") }else{ track[[i]] <- FALSE } diff --git a/R/ds.isValid.R b/R/ds.isValid.R index da48891ca..7527a6f90 100644 --- a/R/ds.isValid.R +++ b/R/ds.isValid.R @@ -59,11 +59,9 @@ #' ds.isValid <- function(x=NULL, datasources=NULL, classConsistencyCheck=TRUE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input vector") # call the server side function that does the job and return its output cally <- call("isValidDS", x) diff --git a/R/ds.kurtosis.R b/R/ds.kurtosis.R index 775f14d81..52c58825f 100644 --- a/R/ds.kurtosis.R +++ b/R/ds.kurtosis.R @@ -29,14 +29,12 @@ #' ds.kurtosis <- function(x=NULL, method=1, type='both', datasources=NULL, classConsistencyCheck=FALSE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input vector") if(!all(method %in% c(1,2,3))){ - stop("method must be an integer between 1 and 3", call.=FALSE) + cli_abort("{.arg method} must be {.or {.val {1:3}}}, not {.val {method}}.") } # enable valid aliases for "type" argument @@ -44,7 +42,7 @@ ds.kurtosis <- function(x=NULL, method=1, type='both', datasources=NULL, classCo if(type == 'split' | type == 'splits' | type == 's') type <- 'split' if(type == 'both' | type == 'b' ) type <- 'both' if(type != 'combine' & type != 'split' & type != 'both'){ - stop('Function argument "type" has to be either "both", "combine" or "split"', call.=FALSE) + .abortInvalidChoice("type", c("both", "combine", "split")) } if (type=='split' | type=='both'){ @@ -65,7 +63,7 @@ ds.kurtosis <- function(x=NULL, method=1, type='both', datasources=NULL, classCo #global.var <- ds.var(x, type='combine')$Global.Variance[,'EstimatedVar'] if (is.na(global.mean)){ - stop("FAILED: The number of valid observations in one or more studies is less than nfilter.tab. \n Check that by using the argument type=='split'", call.=FALSE) + cli_abort(c("The number of valid observations in at least one study is less than {.code nfilter.tab}.", "i" = "Use {.code type = \"split\"} to check each study.")) }else{ calltext.combined <- call("kurtosisDS2", x, global.mean) output.combined <- DSI::datashield.aggregate(datasources, calltext.combined) diff --git a/R/ds.length.R b/R/ds.length.R index 5db7d1e37..4cc1edb2a 100644 --- a/R/ds.length.R +++ b/R/ds.length.R @@ -75,11 +75,9 @@ #' ds.length <- function(x=NULL, type='both', datasources=NULL, classConsistencyCheck=TRUE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input object!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input object") ################################################################################################### # MODULE: EXTEND "type" argument to include "both" and enable valid aliases # @@ -87,7 +85,7 @@ ds.length <- function(x=NULL, type='both', datasources=NULL, classConsistencyChe if(type == 'split' | type == 'splits' | type == 's') type <- 'split' # if(type == 'both' | type == 'b' ) type <- 'both' # if(type != 'combine' & type != 'split' & type != 'both'){ # - stop('Function argument "type" has to be either "both", "combine" or "split"', call.=FALSE) # + .abortInvalidChoice("type", c("both", "combine", "split")) # } # call the server-side function @@ -123,7 +121,7 @@ ds.length <- function(x=NULL, type='both', datasources=NULL, classConsistencyChe out <- c(lengths, pooled.length) names(out) <- c(outputnames, paste0('total length of ', x, ' in all studies combined')) }else{ - stop('Function argument "type" has to be either "both", "combine" or "split"') + .abortInvalidChoice("type", c("both", "combine", "split")) } } } diff --git a/R/ds.levels.R b/R/ds.levels.R index 337a27591..f55adf91c 100644 --- a/R/ds.levels.R +++ b/R/ds.levels.R @@ -59,11 +59,9 @@ #' ds.levels <- function(x=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input vector") cally <- call("levelsDS", x) results <- DSI::datashield.aggregate(datasources, cally) diff --git a/R/ds.lexis.R b/R/ds.lexis.R index fc0532c4f..c7042b09b 100644 --- a/R/ds.lexis.R +++ b/R/ds.lexis.R @@ -203,26 +203,21 @@ #' ds.lexis<-function(data=NULL, intervalWidth=NULL, idCol=NULL, entryCol=NULL, exitCol=NULL, statusCol=NULL, variables=NULL, expandDF=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if user have provided the name of the column that holds the subject ids - if(is.null(idCol)){ - stop("Please provide the name of the column that holds the subject IDs!", call.=FALSE) - } + .checkArgProvided(idCol, "the name of the column that holds subject IDs") # check if user have provided the name of the column that holds failure information - if(is.null(statusCol)){ - stop("Please provide the name of the column that holds 'failure' information!", call.=FALSE) - } + .checkArgProvided(statusCol, "the name of the column that holds failure information") # check if user have provided the name of the column that holds exit times - if(is.null(exitCol)){ - stop("Please provide the name of the column that holds the exit times (i.e. end of follow up time)!", call.=FALSE) - } + .checkArgProvided(exitCol, "the name of the column that holds exit times") # if no valid value provided for 'intervalWidth' instruct user to specify one - if(any(is.null(intervalWidth))||any(is.na(intervalWidth))||any(intervalWidth==0)){ - stop("Please provide a (non-zero) single numeric value or vector to identify the survival time intervals", call.=FALSE) + .checkArgProvided(intervalWidth, "a non-zero numeric value or vector") + if(any(is.na(intervalWidth))||any(intervalWidth==0)){ + cli_abort("{.arg intervalWidth} must be a non-zero numeric value or vector, not {.val {intervalWidth}}.") } # if no value spcified for output (expanded) data set, then specify a default diff --git a/R/ds.list.R b/R/ds.list.R index 3ec7707b8..b75dac9f8 100644 --- a/R/ds.list.R +++ b/R/ds.list.R @@ -56,16 +56,12 @@ #' ds.list <- function(x=NULL, newobj=NULL, datasources=NULL, classConsistencyCheck=TRUE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("x=NULL. Please provide the names of the objects to coerce into a list!", call.=FALSE) - } + .checkArgProvided(x, "the names of the objects to coerce into a list") # create a name by default if user did not provide a name for the new variable - if(is.null(newobj)){ - newobj <- "list.newobj" - } + newobj <- .resolveNewobjName(newobj, "list.newobj") # get the variable names xnames <- extract(x) diff --git a/R/ds.listDisclosureSettings.R b/R/ds.listDisclosureSettings.R index f115bdb28..af0350f17 100644 --- a/R/ds.listDisclosureSettings.R +++ b/R/ds.listDisclosureSettings.R @@ -101,7 +101,7 @@ #' } #' ds.listDisclosureSettings <- function(datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # CALL THE MAIN SERVER SIDE FUNCTION calltext <- call("listDisclosureSettingsDS") diff --git a/R/ds.lmerSLMA.R b/R/ds.lmerSLMA.R index 3f0f5cfc0..9b1f73a87 100644 --- a/R/ds.lmerSLMA.R +++ b/R/ds.lmerSLMA.R @@ -206,23 +206,14 @@ ds.lmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.me control_value = NULL, optimizer = NULL, verbose = 0, notify.of.progress=FALSE, assign=FALSE, newobj=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # verify that 'formula' was set - if(is.null(formula)){ - stop(" Please provide a valid regression formula!", call.=FALSE) - } + .checkArgProvided(formula, "a valid regression formula") # check if user gave offset or weights directly in formula, if so the argument 'offset' or 'weights' # to provide name of offset or weights variable - if(sum(as.numeric(grepl('offset', formula, ignore.case=TRUE)))>0 || - sum(as.numeric(grepl('weights', formula, ignore.case=TRUE)))>0) - { - message("\n\n WARNING: you may have specified an offset or regression weights") - message("\n as part of the model formula. In ds.glm (unlike the usual glm in R)") - message("\n you must specify an offset or weights separately from the formula") - message("\n using the offset or weights argument.\n\n") - } + .checkOffsetInFormula(formula) formula <- stats::as.formula(formula) @@ -231,7 +222,7 @@ ds.lmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.me # beginning of optional checks - the process stops if any of these checks fails # if(checks){ - message(" -- Verifying the variables in the model") + cli_inform("Verifying the variables in the model.") # call the function that checks the variables in the formula are defined (exist) on the server site and are not missing at complete glmChecks(formula, dataName, offset, weights, datasources) @@ -255,8 +246,7 @@ ds.lmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.me if(!is.null(control_type) && is.null(control_value)) { - errorMessage.cv<-"ERROR: if control_type is non-null, you must specify a valid control_value eg control_value<-1.0e-7" - return(list(errorMessage=errorMessage.cv)) + cli_abort(c("{.arg control_value} must be set when {.arg control_type} is set, not {.code NULL}.", "i" = "For example, {.code control_value = 1.0e-7}.")) } if(!is.null(control_value)) @@ -273,9 +263,7 @@ ds.lmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.me if(!is.null(optimizer)&&optimizer!="nloptwrap") { - errorMessage.opt<-"ERROR: the only optimizer currently available for lmer is 'nloptwrap', please respecify" - message("\n",errorMessage.opt,"\n") - return(list(errorMessage=errorMessage.opt)) + .abortInvalidChoice("optimizer", "nloptwrap") } @@ -286,12 +274,10 @@ ds.lmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.me if(assign==TRUE){ - if(is.null(newobj)){ - newobj <- "new.lmer.obj" - } + newobj <- .resolveNewobjName(newobj, "new.lmer.obj") if (notify.of.progress) { - message("\n\nSAVING SERVERSIDE lmerMod OBJECT AS: <",newobj,">\n\n") + cli_inform("Saving server-side lmerMod object as {.val {newobj}}.") } calltext.2 <- call('lmerSLMADS.assign', formula, offset, weights, dataName, REML, @@ -331,17 +317,16 @@ ds.lmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.me { for(sse in study.with.errors) { - message("\n","Error report from second serverside function for study",sse,"\n") - message("############################################################","\n") - message(unlist(study.summary[[sse]][[1]]),"\n") - message(unlist(study.summary[[sse]][[2]]),"\n\n") + cli_inform("Error report from second server-side function for {.val {names(datasources)[sse]}}.") + cli_verbatim(unlist(study.summary[[sse]][[1]])) + cli_verbatim(unlist(study.summary[[sse]][[2]])) num.messages<-length(study.summary[[sse]])-2 for(m in 1:num.messages) { if(!is.null(unlist(study.summary[[sse]][[2+m]]))) { - message(unlist(study.summary[[sse]][[2+m]]),"\n\n") + cli_verbatim(as.character(unlist(study.summary[[sse]][[2+m]]))) } } } @@ -349,8 +334,7 @@ ds.lmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.me if(all.studies.valid) { - message("\nAll studies passed disclosure tests\n") - message("Please check for convergence warnings in the study summaries\n\n\n") + cli_inform(c("All studies passed disclosure tests.", "i" = "Check for convergence warnings in the study summaries.")) } } @@ -476,8 +460,7 @@ ds.lmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.me if(!coefficient.vectors.match){ - message("\n\nModels in different sources vary in structure\nplease match coefficients for meta-analysis individually\n") - message("nYou can use the DataSHIELD generated estimates and standard errors as the basis for a meta-analysis\nbut carry out the final pooling step independently of DataSHIELD using whatever meta-analysis package you wish\n\n") + cli_inform(c("Models in different sources vary in structure.", "i" = "Match coefficients for meta-analysis individually.", "*" = "You can use the DataSHIELD estimates and standard errors as the basis for a meta-analysis, but carry out the final pooling step independently of DataSHIELD.")) return(list(output.summary=output.summary)) } @@ -540,10 +523,10 @@ for(q in 1:numstudies) if (notify.of.progress) { - message("Convergence information\n") + cli_inform("Convergence information:") for(r in 1:numstudies) { - message(full.error.message[r],"\n") + cli_inform("{full.error.message[r]}") } } diff --git a/R/ds.log.R b/R/ds.log.R index ca2364619..b9663f070 100644 --- a/R/ds.log.R +++ b/R/ds.log.R @@ -58,15 +58,11 @@ #' ds.log <- function(x=NULL, base=exp(1), newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input vector") - if(is.null(newobj)){ - newobj <- "log.newobj" - } + newobj <- .resolveNewobjName(newobj, "log.newobj") cally <- call("logDS", x, base) DSI::datashield.assign(datasources, newobj, cally) diff --git a/R/ds.ls.R b/R/ds.ls.R index 7377d59ec..677845b0f 100644 --- a/R/ds.ls.R +++ b/R/ds.ls.R @@ -119,7 +119,7 @@ #' @export ds.ls <- function(search.filter=NULL, env.to.search=1L, search.GlobalEnv=TRUE, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # make default to .GlobalEnv unambiguous if(search.GlobalEnv||is.null(env.to.search)){ @@ -160,10 +160,7 @@ if(!is.null(transmit.object)) if(original.code.problem==TRUE) { - # return.message<-paste0("Warning: Code replacing wildcard (i.e. '",replacement string,"' appears in your original code -please respecify") - return.message<-paste0("Warning: Code replacing wildcard (i.e. '",input.string, - "') is '",replacement.string,"' but this appears in your original search filter string - please respecify") - return(return.message) + cli_abort(c("The code that replaces the wildcard ({.val {input.string}}) is {.val {replacement.string}}, which also appears in your search filter.", "i" = "Respecify the filter.")) } } } diff --git a/R/ds.lspline.R b/R/ds.lspline.R index 2fe8471ba..b7c005910 100644 --- a/R/ds.lspline.R +++ b/R/ds.lspline.R @@ -25,20 +25,14 @@ #' ds.lspline <- function(x, knots = NULL, marginal = FALSE, names = NULL, newobj = NULL, datasources = NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input variable x!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input variable") - if(is.null(knots)){ - stop("Please provide a vector of knots!", call.=FALSE) - } + .checkArgProvided(knots, "a vector of knots") # create a name by default if user did not provide a name for the new variable - if(is.null(newobj)){ - newobj <- "lspline.newobj" - } + newobj <- .resolveNewobjName(newobj, "lspline.newobj") # now do the business calltext <- call("lsplineDS", x, knots, marginal, names) diff --git a/R/ds.make.R b/R/ds.make.R index 2e9cbea58..c396090f3 100644 --- a/R/ds.make.R +++ b/R/ds.make.R @@ -132,16 +132,12 @@ #' ds.make<-function(toAssign=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(toAssign)){ - stop("Please give the name of object to assign or an expression to evaluate and assign.!\n", call.=FALSE) - } + .checkArgProvided(toAssign, "the name of the object to assign or an expression to evaluate") # create a name by default if user did not provide a name for the new variable - if(is.null(newobj)){ - newobj <- "make.newobj" - } + newobj <- .resolveNewobjName(newobj, "make.newobj") # now do the business DSI::datashield.assign(datasources, newobj, as.symbol(toAssign)) diff --git a/R/ds.matrix.R b/R/ds.matrix.R index 5813ebe09..01c62683f 100644 --- a/R/ds.matrix.R +++ b/R/ds.matrix.R @@ -145,25 +145,19 @@ ds.matrix <- function(mdata = NA, from="clientside.scalar", nrows.scalar=NULL, ncols.scalar=NULL, byrow = FALSE, dimnames = NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if a value has been provided for mdata - if(is.null(mdata)){ - return("Error: mdata must be a character string, a numeric vector or a scalar") - } + .checkArgProvided(mdata, "a character string, numeric vector or scalar") # if no value spcified for output object, then specify a default - if(is.null(newobj)){ - newobj <- "matrix.newobj" - } + newobj <- .resolveNewobjName(newobj, "matrix.newobj") #process mdata to make transmittable depending on #Check that valid from has been specified if(from!="serverside.vector"&&from!="serverside.scalar"&&from!="clientside.scalar") { - message(" FAILED: must be specified as one of the following - 'serverside.vector', - 'serverside.scalar', 'clientside.scalar'\n\n") - return('Please respecify') + .abortInvalidChoice("from", c("serverside.vector", "serverside.scalar", "clientside.scalar")) } if(from=="serverside.vector"||from=="serverside.scalar"){ diff --git a/R/ds.matrixDet.R b/R/ds.matrixDet.R index 97bcbff36..da7bc604f 100644 --- a/R/ds.matrixDet.R +++ b/R/ds.matrixDet.R @@ -81,12 +81,10 @@ #' ds.matrixDet<-function(M1=NULL, newobj=NULL, logarithm=FALSE, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if user has provided the name of matrix representing M1 - if(is.null(M1)){ - return("Error: Please provide the name of the matrix representing M1") - } + .checkArgProvided(M1, "the name of the matrix that represents M1") # if no value or invalid value specified for logarithm, then specify a default if(is.null(logarithm)){ @@ -98,9 +96,7 @@ ds.matrixDet<-function(M1=NULL, newobj=NULL, logarithm=FALSE, datasources=NULL){ } # if no value specified for output object, then specify a default - if(is.null(newobj)){ - newobj <- "matrixdet.newobj" - } + newobj <- .resolveNewobjName(newobj, "matrixdet.newobj") # CALL THE MAIN SERVER SIDE ASSIGN FUNCTION calltext <- call("matrixDetDS2", M1, logarithm) diff --git a/R/ds.matrixDet.report.R b/R/ds.matrixDet.report.R index e2b8061cc..0bc18729b 100644 --- a/R/ds.matrixDet.report.R +++ b/R/ds.matrixDet.report.R @@ -77,12 +77,10 @@ #' ds.matrixDet.report<-function(M1=NULL, logarithm=FALSE, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if user has provided the name of matrix representing M1 - if(is.null(M1)){ - return("Error: Please provide the name of the matrix representing M1") - } + .checkArgProvided(M1, "the name of the matrix that represents M1") # if no value or invalid value specified for logarithm, then specify a default if(is.null(logarithm)) diff --git a/R/ds.matrixDiag.R b/R/ds.matrixDiag.R index 4e03f1d01..a53ea007a 100644 --- a/R/ds.matrixDiag.R +++ b/R/ds.matrixDiag.R @@ -175,28 +175,20 @@ #' ds.matrixDiag<-function(x1=NULL, aim=NULL, nrows.scalar=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if a value has been provided for x1 - if(is.null(x1)){ - return("Error: x1 must have a value which is a character string, a numeric vector or a scalar") - } + .checkArgProvided(x1, "a character string, numeric vector or scalar") # if no value spcified for output object, then specify a default - if(is.null(newobj)) - { - newobj <- "matrixdiag.newobj" - } + newobj <- .resolveNewobjName(newobj, "matrixdiag.newobj") #process x1 to make transmittable depending on aim #Check that valid aim has been specified if(aim!="serverside.vector.2.matrix"&&aim!="serverside.scalar.2.matrix"&&aim!="serverside.matrix.2.vector"&& aim!="clientside.vector.2.matrix"&&aim!="clientside.scalar.2.matrix") { - message(" FAILED: aim must be specified as one of the following - 'serverside.vector.2.matrix', - 'serverside.scalar.2.matrix', 'serverside.matrix.2.vector', - 'clientside.vector.2.matrix', 'clientside.scalar.2.matrix'\n\n") - return('Please respecify') + .abortInvalidChoice("aim", c("serverside.vector.2.matrix", "serverside.scalar.2.matrix", "serverside.matrix.2.vector", "clientside.vector.2.matrix", "clientside.scalar.2.matrix")) } if(aim=="serverside.vector.2.matrix"||aim=="serverside.scalar.2.matrix"||aim=="serverside.matrix.2.vector") diff --git a/R/ds.matrixDimnames.R b/R/ds.matrixDimnames.R index b5db1fee1..88e0864a0 100644 --- a/R/ds.matrixDimnames.R +++ b/R/ds.matrixDimnames.R @@ -83,17 +83,13 @@ ds.matrixDimnames<-function(M1=NULL, dimnames=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if user has provided the name of matrix representing M1 - if(is.null(M1)){ - return("Error: Please provide the name of the matrix representing M1") - } + .checkArgProvided(M1, "the name of the matrix that represents M1") # if no value specified for output object, then specify a default - if(is.null(newobj)){ - newobj <- "matrixdimnames.newobj" - } + newobj <- .resolveNewobjName(newobj, "matrixdimnames.newobj") diff --git a/R/ds.matrixInvert.R b/R/ds.matrixInvert.R index a8902aac9..7c81f02c2 100644 --- a/R/ds.matrixInvert.R +++ b/R/ds.matrixInvert.R @@ -79,17 +79,13 @@ #' ds.matrixInvert<-function(M1=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if user has provided the name of matrix representing M1 - if(is.null(M1)){ - return("Error: Please provide the name of the matrix representing M1") - } + .checkArgProvided(M1, "the name of the matrix that represents M1") # if no value specified for output object, then specify a default - if(is.null(newobj)){ - newobj <- "matrixinvert.newobj" - } + newobj <- .resolveNewobjName(newobj, "matrixinvert.newobj") # CALL THE MAIN SERVER SIDE FUNCTION calltext <- call("matrixInvertDS", M1) diff --git a/R/ds.matrixMult.R b/R/ds.matrixMult.R index bdef9abe2..cb7c808d8 100644 --- a/R/ds.matrixMult.R +++ b/R/ds.matrixMult.R @@ -94,26 +94,20 @@ #' ds.matrixMult<-function(M1=NULL, M2=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if user has provided the name of matrix representing M1 - if(is.null(M1)){ - return("Error: Please provide the name of the matrix representing M1") - } + .checkArgProvided(M1, "the name of the matrix that represents M1") # check if user has provided the name of matrix representing M2 - if(is.null(M2)){ - return("Error: Please provide the name of the matrix representing M2") - } + .checkArgProvided(M2, "the name of the matrix that represents M2") # if no value spcified for output object, then specify a default - if(is.null(newobj)){ - newobj <- "matrixmult.newobj" - } + newobj <- .resolveNewobjName(newobj, "matrixmult.newobj") # CALL THE MAIN SERVER SIDE FUNCTION calltext <- call("matrixMultDS", M1, M2) diff --git a/R/ds.matrixTranspose.R b/R/ds.matrixTranspose.R index 9286bb286..a7dd8347c 100644 --- a/R/ds.matrixTranspose.R +++ b/R/ds.matrixTranspose.R @@ -82,17 +82,13 @@ #' ds.matrixTranspose<-function(M1=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if user has provided the name of matrix representing M1 - if(is.null(M1)){ - return("Error: Please provide the name of the matrix representing M1") - } + .checkArgProvided(M1, "the name of the matrix that represents M1") # if no value spcified for output object, then specify a default - if(is.null(newobj)){ - newobj <- "matrixtranspose.newobj" - } + newobj <- .resolveNewobjName(newobj, "matrixtranspose.newobj") # CALL THE MAIN SERVER SIDE FUNCTION calltext <- call("matrixTransposeDS", M1) diff --git a/R/ds.mdPattern.R b/R/ds.mdPattern.R index 0c083e946..e9c974269 100644 --- a/R/ds.mdPattern.R +++ b/R/ds.mdPattern.R @@ -115,11 +115,9 @@ #' ds.mdPattern <- function(x = NULL, type = 'split', datasources = NULL, classConsistencyCheck = TRUE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of a data frame or matrix!", call.=FALSE) - } + .checkArgProvided(x, "the name of a data.frame or matrix") # Get study names study_names <- names(datasources) @@ -145,13 +143,7 @@ ds.mdPattern <- function(x = NULL, type = 'split', datasources = NULL, classCons invalid_studies <- names(results)[sapply(results, function(r) !r$valid)] if(any_invalid){ - warning( - "Disclosure control: Some studies have suppressed patterns (below threshold).\n", - " Studies with suppressed patterns: ", paste(invalid_studies, collapse=", "), "\n", - " These patterns are EXCLUDED from pooling to prevent disclosure.\n", - " Pooled counts may underestimate the true total.", - call. = FALSE - ) + cli_warn(c("Some studies have patterns suppressed by disclosure control.", "i" = "Affected studies: {.val {invalid_studies}}.", "!" = "These patterns are excluded from pooling, so pooled counts may underestimate the true total.")) } # Extract patterns from each study @@ -160,17 +152,20 @@ ds.mdPattern <- function(x = NULL, type = 'split', datasources = NULL, classCons # Check if all patterns have the same variables (columns) n_vars <- sapply(patterns_list, ncol) if(length(unique(n_vars)) > 1){ - stop("Cannot pool patterns: studies have different numbers of variables", call.=FALSE) + counts <- paste0(vapply(names(n_vars), function(study) cli::format_inline("{.val {study}}"), character(1)), " has ", n_vars - 1, " variables.") + names(counts) <- rep("x", length(counts)) + cli_abort(c("Can't pool patterns because studies have different numbers of variables.", counts)) } # md.pattern orders variable columns by missingness, which differs across studies, # so align them by name to study 1's order (the last, unnamed column stays last) var_names <- colnames(patterns_list[[1]]) var_cols <- var_names[-length(var_names)] + caller <- environment() patterns_list <- lapply(patterns_list, function(pattern){ study_vars <- colnames(pattern)[-ncol(pattern)] if(!setequal(study_vars, var_cols)){ - stop("Cannot pool patterns: studies have different variables", call.=FALSE) + cli_abort(c("Can't pool patterns because studies have different variables.", "x" = "Not in every study: {.val {union(setdiff(study_vars, var_cols), setdiff(var_cols, study_vars))}}."), call = caller) } pattern[, c(match(var_cols, study_vars), ncol(pattern)), drop = FALSE] }) @@ -208,7 +203,7 @@ ds.mdPattern <- function(x = NULL, type = 'split', datasources = NULL, classCons )) } else { - stop("Argument 'type' must be either 'split' or 'combine'", call.=FALSE) + .abortInvalidChoice("type", c("split", "combine")) } } diff --git a/R/ds.mean.R b/R/ds.mean.R index accbc2c3f..a83c8e733 100644 --- a/R/ds.mean.R +++ b/R/ds.mean.R @@ -97,11 +97,9 @@ #' ds.mean <- function(x=NULL, type='split', save.mean.Nvalid=FALSE, datasources=NULL, classConsistencyCheck=FALSE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input object!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input object") ################################################################################################### #MODULE: EXTEND "type" argument to include "both" and enable valid alisases # @@ -109,7 +107,7 @@ if(type == 'combine' | type == 'combined' | type == 'combines' | type == 'c') ty if(type == 'split' | type == 'splits' | type == 's') type <- 'split' # if(type == 'both' | type == 'b' ) type <- 'both' # if(type != 'combine' & type != 'split' & type != 'both'){ # - stop('Function argument "type" has to be either "both", "combine" or "split"', call.=FALSE) # + .abortInvalidChoice("type", c("both", "combine", "split")) # } cally <- call("meanDS", x) diff --git a/R/ds.meanSdGp.R b/R/ds.meanSdGp.R index 810c5c1b8..07ea62795 100644 --- a/R/ds.meanSdGp.R +++ b/R/ds.meanSdGp.R @@ -103,15 +103,11 @@ #' ds.meanSdGp <- function(x=NULL, y=NULL, type='both', datasources=NULL, classConsistencyCheck=TRUE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input vector") - if(is.null(y)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(y, "the name of the input vector") # names of the studies stdnames <- names(datasources) @@ -130,8 +126,8 @@ ds.meanSdGp <- function(x=NULL, y=NULL, type='both', datasources=NULL, classCons if(classConsistencyCheck){ # check the summarised variable (x) and grouping factor (y) each have the # same class in all studies - .checkClassConsistency(output, field = "class.x", object_name = x) - .checkClassConsistency(output, field = "class.index", object_name = y) + .checkClassConsistency(output, field = "class.x", objectName = x) + .checkClassConsistency(output, field = "class.index", objectName = y) } numsources <- length(output) @@ -142,8 +138,7 @@ ds.meanSdGp <- function(x=NULL, y=NULL, type='both', datasources=NULL, classCons } if(all.tables.valid<1){ - warning.message<-"At least 1 cell count is 1-nfilter, please regroup" - return(warning.message) + cli_abort(c("At least one cell count is below {.code nfilter.tab}.", "i" = "Regroup the data and try again.")) } if(all.tables.valid==1){ diff --git a/R/ds.merge.R b/R/ds.merge.R index 2eae96207..3495e1471 100644 --- a/R/ds.merge.R +++ b/R/ds.merge.R @@ -114,42 +114,30 @@ ds.merge <- function(x.name=NULL,y.name=NULL, by.x.names=NULL, by.y.names=NULL,all.x=FALSE,all.y=FALSE, sort=TRUE, suffixes = c(".x",".y"), no.dups=TRUE, incomparables=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # dataframe names - if(is.null(x.name)){ - stop("Please provide the name (eg 'name1') of first dataframe to be merged (called x) ", call.=FALSE) - } + .checkArgProvided(x.name, "the name of the first data.frame to merge") - if(is.null(y.name)){ - stop("Please provide the name (eg 'name2') of second dataframe to be merged (called y) ", call.=FALSE) - } + .checkArgProvided(y.name, "the name of the second data.frame to merge") # names of columns to merge on (may be more than one) - if(is.null(by.x.names)){ - stop("Please provide the names of columns in x dataframe on which to merge (eg c('id', 'time'))", call.=FALSE) - } + .checkArgProvided(by.x.names, "the names of the columns in x to merge on") - if(is.null(by.y.names)){ - stop("Please provide the names of columns in y dataframe on which to merge (eg c('id', 'time'))", call.=FALSE) - } + .checkArgProvided(by.y.names, "the names of the columns in y to merge on") # make transmittable via parser by.x.names.transmit <- paste(by.x.names, collapse=",") by.y.names.transmit <- paste(by.y.names, collapse=",") # suffixes - if(is.null(suffixes)){ - stop("Please provide the suffixes to append to disambiguate duplicate column names (default = c('.x','.y'))", call.=FALSE) - } + .checkArgProvided(suffixes, "the suffixes that separate duplicate column names") # make transmittable via parser suffixes.transmit <- paste(suffixes, collapse=",") # create a name by default if user did not provide a name for the new dataframe - if(is.null(newobj)){ - newobj <- "merge.newobj" - } + newobj <- .resolveNewobjName(newobj, "merge.newobj") # call the server side function calltext <- call("mergeDS", x.name, y.name, by.x.names.transmit, by.y.names.transmit, all.x, all.y, diff --git a/R/ds.metadata.R b/R/ds.metadata.R index 2e080f017..27bcf8e03 100644 --- a/R/ds.metadata.R +++ b/R/ds.metadata.R @@ -50,19 +50,18 @@ ds.metadata = function(x=NULL, datasources=NULL) { - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) ##################################################################################### #MODULE 3: SET UP KEY VARIABLES ALLOWING FOR DIFFERENT INPUT FORMATS # - if (is.null(x)){ # - stop("Please provide the name of the object!", call.=FALSE) # - } # + .checkArgProvided(x, "the name of an object") # ##################################################################################### ##################################################################################### #MODULE 4: CHECK CONSISTANCY OF VARIABLE NAME (SINGLE) # if ((! is.character(x)) || (length(x) != 1)){ # - stop("Please provide the name of the object!", call.=FALSE) # + supplied <- .describeSupplied(x) # nolint: object_usage_linter. Used in the cli template + cli_abort("{.arg x} must be a single character string, not {supplied}.") # } # ##################################################################################### diff --git a/R/ds.mice.R b/R/ds.mice.R index 38e271572..795a1a30e 100644 --- a/R/ds.mice.R +++ b/R/ds.mice.R @@ -49,12 +49,10 @@ ds.mice <- function(data=NULL, m=5, maxit=5, method=NULL, predictorMatrix=NULL, post=NULL, seed=NA, newobj_mids=NULL, newobj_df=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # verify that 'data' was set - if(is.null(data)){ - stop("Please provide the name of the dataframe or matrix that contains the incomplete data!", call.=FALSE) - } + .checkArgProvided(data, "the name of the data.frame or matrix that holds the incomplete data") if(!is.null(method)){ method <- paste0(as.character(method), collapse=",") diff --git a/R/ds.names.R b/R/ds.names.R index 1466ce8d3..6d40a034d 100644 --- a/R/ds.names.R +++ b/R/ds.names.R @@ -69,11 +69,9 @@ #' ds.names <- function(xname=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(xname)){ - stop("Please provide the name of the input list!", call.=FALSE) - } + .checkArgProvided(xname, "the name of the input list") calltext <- call("namesDS", xname) output <- DSI::datashield.aggregate(datasources, calltext) diff --git a/R/ds.ns.R b/R/ds.ns.R index e1e101ef0..6dd598c63 100644 --- a/R/ds.ns.R +++ b/R/ds.ns.R @@ -36,12 +36,10 @@ ds.ns <- function(x, df = NULL, knots = NULL, intercept = FALSE, Boundary.knots = NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # create a name by default if user did not provide a name for the new variable - if(is.null(newobj)){ - newobj <- "ns.newobj" - } + newobj <- .resolveNewobjName(newobj, "ns.newobj") # now do the business calltext <- call("nsDS", x, df, knots, intercept, Boundary.knots) diff --git a/R/ds.numNA.R b/R/ds.numNA.R index b5ad89dce..9b1eceeae 100644 --- a/R/ds.numNA.R +++ b/R/ds.numNA.R @@ -56,11 +56,9 @@ #' ds.numNA <- function(x=NULL, datasources=NULL, classConsistencyCheck=TRUE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of a vector!", call.=FALSE) - } + .checkArgProvided(x, "the name of a vector") cally <- call("numNaDS", x) results <- DSI::datashield.aggregate(datasources, cally) diff --git a/R/ds.qlspline.R b/R/ds.qlspline.R index ca808fb03..9240a7f3e 100644 --- a/R/ds.qlspline.R +++ b/R/ds.qlspline.R @@ -33,20 +33,14 @@ #' ds.qlspline <- function(x, q, na.rm = TRUE, marginal = FALSE, names = NULL, newobj = NULL, datasources = NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input variable x!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input variable") - if(is.null(q)){ - stop("Argument 'q' is missing, with no default!", call.=FALSE) - } + .checkArgProvided(q, "a number of quantiles") # create a name by default if user did not provide a name for the new variable - if(is.null(newobj)){ - newobj <- "qlspline.newobj" - } + newobj <- .resolveNewobjName(newobj, "qlspline.newobj") # now do the business calltext <- call("qlsplineDS", x, q, na.rm, marginal, names) diff --git a/R/ds.quantileMean.R b/R/ds.quantileMean.R index 4f037f1f7..e0496e005 100644 --- a/R/ds.quantileMean.R +++ b/R/ds.quantileMean.R @@ -69,14 +69,12 @@ #' ds.quantileMean <- function(x=NULL, type='combine', datasources=NULL, classConsistencyCheck=FALSE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input vector") if (! all(type %in% c("combine", "split"))) { - stop('Function argument "type" has to be either "combine" or "split"', call.=FALSE) + .abortInvalidChoice("type", c("combine", "split")) } # get the server function that produces the quantiles @@ -110,13 +108,13 @@ ds.quantileMean <- function(x=NULL, type='combine', datasources=NULL, classConsi names(output) <- c("5%","10%","25%","50%","75%","90%","95%","Mean") if(type=="combine"){ - message(" Quantiles of the pooled data") + cli_inform("Quantiles of the pooled data.") return(output) }else{ if(type=="split"){ return(quants) }else{ - stop('Function argument "type" has to be either "combine" or "split"', call.=FALSE) + .abortInvalidChoice("type", c("combine", "split")) } } } diff --git a/R/ds.rBinom.R b/R/ds.rBinom.R index 35b8a3ad2..2863b865b 100644 --- a/R/ds.rBinom.R +++ b/R/ds.rBinom.R @@ -106,31 +106,14 @@ #' @export ds.rBinom<-function(samp.size=1,size=0,prob=1, newobj=NULL, seed.as.integer=NULL, return.full.seed.as.set=FALSE, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # create a name by default if user did not provide a name for the new variable - if(is.null(newobj)){ - newobj <- "rbinom.newobj" - } + newobj <- .resolveNewobjName(newobj, "rbinom.newobj") ######################## #TEST SEED PRIMING VALUE -seed.valid<-0 - -if(is.null(seed.as.integer)){ -seed.as.text<-"NULL" -seed.valid<-1 -} - -if(is.numeric(seed.as.integer)){ -seed.as.text<-as.character(seed.as.integer) -seed.valid<-1 -} - -if(seed.valid==0){ -mess1<-("ERROR failed: seed.as.integer must be set as an integer [numeric] or left NULL") -return(mess1) -} +seed.as.text <- .seedAsText(seed.as.integer) ################################################################################### #samp.size is either a numeric scalar or a numeric vector set @@ -142,20 +125,11 @@ return(mess1) #Such serverside vectors must be named in inverted commas. These get #stripped off when the vector name is passed to the serverside. -arguments.valid<-1 - -if(is.null(samp.size)||is.null(size)||is.null(prob)||is.null(newobj)){ -arguments.valid<-0 -} - -if(!arguments.valid){ -mess2<-("ERROR: appropriate values must be set for samp.size, size, prob, and newobj name") -return(mess2) -} +.checkArgsSet(samp.size = samp.size, size = size, prob = prob, newobj = newobj) numsources<-length(datasources) -size<-.expand_to_studies(size, "size", numsources) -prob<-.expand_to_studies(prob, "prob", numsources) +size<-.expandToStudies(size, "size", numsources) +prob<-.expandToStudies(prob, "prob", numsources) size.valid<-1 if(is.numeric(size)){ @@ -165,8 +139,7 @@ if(is.numeric(size)){ } if(!size.valid){ -mess3<-("ERROR: size must be > 0") -return(mess3) +cli_abort("{.arg size} must be greater than 0, not {.val {unique(size[size <= 0])}}.") } prob.valid<-1 @@ -177,8 +150,7 @@ if(is.numeric(prob)){ } if(!prob.valid){ -mess4<-("ERROR: prob must lie in range 0 < prob < 1") -return(mess4) +cli_abort("{.arg prob} must be between 0 and 1, not {.val {unique(prob[prob <= 0 | prob >= 1])}}.") } @@ -209,13 +181,12 @@ single.integer.seed<-c(single.integer.seed,seed.as.integer.study.specific) if(seed.as.text=="NULL"){ -message("NO SEED SET IN STUDY",study.id,"\n\n") +cli_inform("No seed set in {.val {names(datasources)[study.id]}}.") } else { ssDS.obj[[study.id]] <- datashield.aggregate(datasources[study.id], call("setSeedDS", seedtext=seed.as.text)) } } -message("\n\n") diff --git a/R/ds.rNorm.R b/R/ds.rNorm.R index d2e035b8b..ff40b3d95 100644 --- a/R/ds.rNorm.R +++ b/R/ds.rNorm.R @@ -120,26 +120,11 @@ ds.rNorm<-function(samp.size=1,mean=0,sd=1, newobj="newObject", seed.as.integer=NULL, return.full.seed.as.set=FALSE, force.output.to.k.decimal.places=9,datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) ######################## #TEST SEED PRIMING VALUE -seed.valid<-0 - -if(is.null(seed.as.integer)){ -seed.as.text<-"NULL" -seed.valid<-1 -} - -if(is.numeric(seed.as.integer)){ -seed.as.text<-as.character(seed.as.integer) -seed.valid<-1 -} - -if(seed.valid==0){ -mess1<-("ERROR failed: seed.as.integer must be set as an integer [numeric] or left NULL") -return(mess1) -} +seed.as.text <- .seedAsText(seed.as.integer) ################################################################################### #samp.size is either a numeric scalar or a numeric vector set @@ -151,21 +136,12 @@ return(mess1) #Such serverside vectors must be named in inverted commas. These get #stripped off when the vector name is passed to the serverside. -arguments.valid<-1 - -if(is.null(samp.size)||is.null(mean)||is.null(sd)||is.null(newobj)){ -arguments.valid<-0 -} - -if(!arguments.valid){ -mess2<-("ERROR: appropriate values must be set for samp.size, mean, sd, and newobj name") -return(mess2) -} +.checkArgsSet(samp.size = samp.size, mean = mean, sd = sd, newobj = newobj) numsources<-length(datasources) -mean<-.expand_to_studies(mean, "mean", numsources) -sd<-.expand_to_studies(sd, "sd", numsources) -force.output.to.k.decimal.places<-.expand_to_studies(force.output.to.k.decimal.places, "force.output.to.k.decimal.places", numsources) +mean<-.expandToStudies(mean, "mean", numsources) +sd<-.expandToStudies(sd, "sd", numsources) +force.output.to.k.decimal.places<-.expandToStudies(force.output.to.k.decimal.places, "force.output.to.k.decimal.places", numsources) sd.valid<-1 if(is.numeric(sd)){ @@ -175,8 +151,7 @@ if(is.numeric(sd)){ } if(!sd.valid){ -mess3<-("ERROR: sd must be > 0") -return(mess3) +cli_abort("{.arg sd} must be greater than 0, not {.val {unique(sd[sd <= 0])}}.") } decimal.places.valid<-1 @@ -185,8 +160,7 @@ decimal.places.valid<-0 } if(!decimal.places.valid){ -mess4<-("ERROR: force.output.to.k.decimal.places must be an integer in range 0-9") -return(mess4) +cli_abort("{.arg force.output.to.k.decimal.places} must be an integer between 0 and 9, not {.val {unique(force.output.to.k.decimal.places[force.output.to.k.decimal.places < 0 | force.output.to.k.decimal.places > 9])}}.") } ################################################################################### @@ -215,12 +189,11 @@ single.integer.seed<-c(single.integer.seed,seed.as.integer.study.specific) if(seed.as.text=="NULL"){ -message("NO SEED SET IN STUDY",study.id,"\n\n") +cli_inform("No seed set in {.val {names(datasources)[study.id]}}.") } ssDS.obj[[study.id]] <- datashield.aggregate(datasources[study.id], call("setSeedDS", seedtext=seed.as.text)) } -message("\n\n") diff --git a/R/ds.rPois.R b/R/ds.rPois.R index c4d56448d..167c956da 100644 --- a/R/ds.rPois.R +++ b/R/ds.rPois.R @@ -102,26 +102,11 @@ #' @export ds.rPois<-function(samp.size=1,lambda=1, newobj="newObject", seed.as.integer=NULL, return.full.seed.as.set=FALSE, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) ######################## #TEST SEED PRIMING VALUE -seed.valid<-0 - -if(is.null(seed.as.integer)){ -seed.as.text<-"NULL" -seed.valid<-1 -} - -if(is.numeric(seed.as.integer)){ -seed.as.text<-as.character(seed.as.integer) -seed.valid<-1 -} - -if(seed.valid==0){ -mess1<-("ERROR failed: seed.as.integer must be set as an integer [numeric] or left NULL") -return(mess1) -} +seed.as.text <- .seedAsText(seed.as.integer) ################################################################################### #samp.size is either a numeric scalar or a numeric vector set @@ -133,19 +118,10 @@ return(mess1) #Such serverside vectors must be named in inverted commas. These get #stripped off when the vector name is passed to the serverside. -arguments.valid<-1 - -if(is.null(samp.size)||is.null(lambda)||is.null(newobj)){ -arguments.valid<-0 -} - -if(!arguments.valid){ -mess2<-("ERROR: appropriate values must be set for samp.size, lambda, and newobj name") -return(mess2) -} +.checkArgsSet(samp.size = samp.size, lambda = lambda, newobj = newobj) numsources<-length(datasources) -lambda<-.expand_to_studies(lambda, "lambda", numsources) +lambda<-.expandToStudies(lambda, "lambda", numsources) lambda.valid<-1 if(is.numeric(lambda)){ @@ -155,8 +131,7 @@ if(is.numeric(lambda)){ } if(!lambda.valid){ -mess3<-("ERROR: lambda must be > 0") -return(mess3) +cli_abort("{.arg lambda} must be greater than 0, not {.val {unique(lambda[lambda <= 0])}}.") } ################################################################################### @@ -185,12 +160,11 @@ single.integer.seed<-c(single.integer.seed,seed.as.integer.study.specific) if(seed.as.text=="NULL"){ -message("NO SEED SET IN STUDY",study.id,"\n\n") +cli_inform("No seed set in {.val {names(datasources)[study.id]}}.") } ssDS.obj[[study.id]] <- datashield.aggregate(datasources[study.id], call("setSeedDS", seedtext=seed.as.text)) } -message("\n\n") diff --git a/R/ds.rUnif.R b/R/ds.rUnif.R index e09ed4910..52bab445d 100644 --- a/R/ds.rUnif.R +++ b/R/ds.rUnif.R @@ -128,26 +128,11 @@ ds.rUnif<-function(samp.size=1,min=0,max=1, newobj="newObject", seed.as.integer=NULL, return.full.seed.as.set=FALSE, force.output.to.k.decimal.places=9,datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) ######################## #TEST SEED PRIMING VALUE -seed.valid<-0 - -if(is.null(seed.as.integer)){ -seed.as.text<-"NULL" -seed.valid<-1 -} - -if(is.numeric(seed.as.integer)){ -seed.as.text<-as.character(seed.as.integer) -seed.valid<-1 -} - -if(seed.valid==0){ -mess1<-("ERROR failed: seed.as.integer must be set as an integer [numeric] or left NULL") -return(mess1) -} +seed.as.text <- .seedAsText(seed.as.integer) ################################################################################### #samp.size is either a numeric scalar or a numeric vector set @@ -159,22 +144,12 @@ return(mess1) #Such serverside vectors must be named in inverted commas. These get #stripped off when the vector name is passed to the serverside. -arguments.valid<-1 - -if(is.null(samp.size)||is.null(min)||is.null(max)||is.null(newobj)){ -arguments.valid<-0 -} - - -if(!arguments.valid){ -mess2<-("ERROR: appropriate values must be set for samp.size, min, max, and newobj name") -return(mess2) -} +.checkArgsSet(samp.size = samp.size, min = min, max = max, newobj = newobj) numsources<-length(datasources) -min<-.expand_to_studies(min, "min", numsources) -max<-.expand_to_studies(max, "max", numsources) -force.output.to.k.decimal.places<-.expand_to_studies(force.output.to.k.decimal.places, "force.output.to.k.decimal.places", numsources) +min<-.expandToStudies(min, "min", numsources) +max<-.expandToStudies(max, "max", numsources) +force.output.to.k.decimal.places<-.expandToStudies(force.output.to.k.decimal.places, "force.output.to.k.decimal.places", numsources) minmax.valid<-1 @@ -187,8 +162,7 @@ if(is.numeric(min) && is.numeric(max)){ } if(!minmax.valid){ -mess3<-("ERROR: max must be greater than min") -return(mess3) +cli_abort(c("{.arg max} must be greater than {.arg min}.", "x" = "{.arg min} is {.val {unique(min)}} and {.arg max} is {.val {unique(max)}}.")) } decimal.places.valid<-1 @@ -197,8 +171,7 @@ decimal.places.valid<-0 } if(!decimal.places.valid){ -mess4<-("ERROR: force.output.to.k.decimal.places must be an integer in range 0-9") -return(mess4) +cli_abort("{.arg force.output.to.k.decimal.places} must be an integer between 0 and 9, not {.val {unique(force.output.to.k.decimal.places[force.output.to.k.decimal.places < 0 | force.output.to.k.decimal.places > 9])}}.") } @@ -230,7 +203,7 @@ single.integer.seed<-c(single.integer.seed,seed.as.integer.study.specific) if(seed.as.text=="NULL"){ -message("NO SEED SET IN STUDY",study.id,"\n") +cli_inform("No seed set in {.val {names(datasources)[study.id]}}.") } else { ssDS.obj[[study.id]] <- datashield.aggregate(datasources[study.id], call("setSeedDS", seedtext=seed.as.text)) diff --git a/R/ds.rbind.R b/R/ds.rbind.R index 995b719e2..618867822 100644 --- a/R/ds.rbind.R +++ b/R/ds.rbind.R @@ -83,30 +83,21 @@ ds.rbind<-function(x=NULL, DataSHIELD.checks=FALSE, force.colnames=NULL, newobj=NULL, datasources=NULL, notify.of.progress=FALSE, classConsistencyCheck=TRUE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide a vector of character strings holding the name of the input elements!", call.=FALSE) - } + .checkArgProvided(x, "a vector of the names of the input elements") if(DataSHIELD.checks){ # call the internal function that checks the input object(s) is(are) of the same legal class in all studies. if(classConsistencyCheck){ - for(i in 1:length(x)){ - typ <- checkClass(datasources, x[i]) - if(!('data.frame' %in% typ) & !('matrix' %in% typ) & !('factor' %in% typ) & !('character' %in% typ) & !('numeric' %in% typ) & !('integer' %in% typ) & !('logical' %in% typ)){ - stop(" Only objects of type 'data.frame', 'matrix', 'numeric', 'integer', 'character', 'factor' and 'logical' are allowed.", call.=FALSE) - } - } + .checkObjectClasses(datasources, x) } } # check newobj not actively declared as null - if(is.null(newobj)){ - newobj <- "rbind.newobj" - } + newobj <- .resolveNewobjName(newobj, "rbind.newobj") #CREATE THE VECTOR OF COLUMN NAMES if(!is.null(force.colnames)){ @@ -124,7 +115,7 @@ calltext1<-call('classDS', testclass.var) next.class <- DSI::datashield.aggregate(datasources, calltext1) class.vector<-c(class.vector,next.class[[1]]) if (notify.of.progress) - message("\n",j," of ", length(x), " elements to combine in step 1 of 2\n") + cli_inform("{j} of {length(x)} elements to combine in step 1 of 2.") } for(j in 1:length(x)) @@ -135,7 +126,7 @@ if(class.vector[j]!="data.frame" && class.vector[j]!="matrix") { colname.vector<-c(colname.vector,test.df) if (notify.of.progress) - message("\n",j," of ", length(x), " elements to combine in step 2 of 2\n") + cli_inform("{j} of {length(x)} elements to combine in step 2 of 2.") } else { @@ -143,11 +134,11 @@ else df.names <- DSI::datashield.aggregate(datasources, calltext2) colname.vector<-c(colname.vector,df.names[[1]]) if (notify.of.progress) - message("\n",j," of ", length(x), " elements to combine in step 2 of 2\n") + cli_inform("{j} of {length(x)} elements to combine in step 2 of 2.") } } if (notify.of.progress) - message("\nBoth steps completed\n") + cli_inform("Both steps completed.") #CHECK FOR DUPLICATE NAMES IN COLUMN NAME VECTOR AND ADD ".k" TO THE kth REPLICATE num.duplicates<-rep(0,length(colname.vector)) diff --git a/R/ds.reShape.R b/R/ds.reShape.R index 209734f2f..26156d1ff 100644 --- a/R/ds.reShape.R +++ b/R/ds.reShape.R @@ -82,14 +82,13 @@ ds.reShape <- function(data.name=NULL, varying=NULL, v.names=NULL, timevar.name="time", idvar.name="id", drop=NULL, direction=NULL, sep=".", newobj="newObject", datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(data.name)){ - stop("Please provide the name of the list that holds the input vectors!", call.=FALSE) - } + .checkArgProvided(data.name, "the name of the list that holds the input vectors") if (!is.character(sep) || (nchar(sep) != 1)){ - stop("'sep' must be a character string", call.=FALSE) + supplied <- .describeSupplied(sep) # nolint: object_usage_linter. Used in the cli template + cli_abort("{.arg sep} must be a single character, not {supplied}.") } if(!is.null(varying)){ diff --git a/R/ds.recodeValues.R b/R/ds.recodeValues.R index 4038c324e..47b342f21 100644 --- a/R/ds.recodeValues.R +++ b/R/ds.recodeValues.R @@ -79,37 +79,34 @@ ds.recodeValues <- function(var.name=NULL, values2replace.vector=NULL, new.values.vector=NULL, missing=NULL, newobj=NULL, datasources=NULL, notify.of.progress=FALSE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check user has provided the name of the variable to be recoded - if(is.null(var.name)){ - stop("Please provide the name of the variable to be recoded: eg 'xxx'", call.=FALSE) - } + .checkArgProvided(var.name, "the name of the variable to recode") # check user has provided the vector specifying the set of values to be replaced if(is.null(values2replace.vector)){ - stop("Please provide a vector in the 'values2replace.vector' argument specifying - the values to be replaced eg c(1,7)", call.=FALSE) + cli_abort(c("{.arg values2replace.vector} must specify the values to replace, not {.code NULL}.", "i" = "For example, {.code c(1, 7)}.")) } # check user has provided the vector specifying the set of values to replace them with - if(is.null(values2replace.vector)){ - stop("Please provide a vector specifying the new values to be set eg c(3,4)", call.=FALSE) + if(is.null(new.values.vector)){ + cli_abort(c("{.arg new.values.vector} must specify the new values, not {.code NULL}.", "i" = "For example, {.code c(3, 4)}.")) } # check values2replace.vector and new.values.vector have the same length if(length(values2replace.vector) != length(new.values.vector)){ - stop("Please ensure that values2replace.vector and new.values.vector have same length and are in the same order", call.=FALSE) + cli_abort(c("{.arg values2replace.vector} and {.arg new.values.vector} must have the same length and order.", "x" = "{.arg values2replace.vector} is {.val {values2replace.vector}}; {.arg new.values.vector} is {.val {new.values.vector}}.")) } # check no duplicate values in values2replace.vector if(length(values2replace.vector) != length(unique(values2replace.vector))){ - stop("No value may appear more than once in the values2replace.vector", call.=FALSE) + cli_abort(c("{.arg values2replace.vector} must not contain duplicate values.", "x" = "Duplicated: {.val {unique(values2replace.vector[duplicated(values2replace.vector)])}}.")) } # simple work around for a bug in the format for values2replace.vector if(any(is.na(values2replace.vector))){ - stop("To recode NAs you need to use the 'missing' argument", call.=FALSE) + cli_abort(c("{.arg values2replace.vector} can't contain {.code NA}.", "x" = "{.arg values2replace.vector} is {.val {values2replace.vector}}.", "i" = "Use {.arg missing} to recode {.code NA} values.")) } if(!is.null(values2replace.vector) & !is.null(new.values.vector)){ @@ -120,9 +117,7 @@ ds.recodeValues <- function(var.name=NULL, values2replace.vector=NULL, new.value new.values.transmit <- NULL } - if(is.null(newobj)){ - newobj <- paste0(var.name, "_recoded") - } + newobj <- .resolveNewobjName(newobj, paste0(var.name, "_recoded")) calltext <- call("recodeValuesDS", var.name, values2replace.transmit, new.values.transmit, missing) DSI::datashield.assign(datasources, newobj, calltext) diff --git a/R/ds.rep.R b/R/ds.rep.R index 72c9177a5..34464bcdd 100644 --- a/R/ds.rep.R +++ b/R/ds.rep.R @@ -96,18 +96,13 @@ ds.rep<-function(x1=NULL, times=NA, length.out=NA, each=1, source.length.out=NULL,source.each=NULL, x1.includes.characters=FALSE,newobj=NULL,datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if a value has been provided for x1 - if(is.null(x1)){ - return("Error: x1 must have a value which is a character string, a numeric vector on the clientside or a scalar") - } + .checkArgProvided(x1, "a character string, a client-side numeric vector or a scalar") # if no value specified for output object, then specify a default - if(is.null(newobj)) - { - newobj <- paste0("seq.vect") - } + newobj <- .resolveNewobjName(newobj, paste0("seq.vect")) #set up aliases for 'clientside', 'serverside' as 'c' and 's' if(source.x1=='c')source.x1<-'clientside' @@ -141,9 +136,7 @@ if(source.each=='s')source.each<-'serverside' #Check that source has been specified if(source.x1!="serverside"&&source.x1!="clientside") { - message(" FAILED: if source.x1 is non-null it must be specified as - one of the following: 'clientside','serverside','c', or 's'\n\n") - return('Please respecify') + .abortInvalidChoice("source.x1", c("clientside", "serverside", "c", "s")) } #process appropriately for source @@ -164,9 +157,7 @@ if(source.each=='s')source.each<-'serverside' #Check that source has been specified if(source.times!="serverside"&&source.times!="clientside"&&!is.null(source.times)) { - message(" FAILED: if source.times is non-null it must be specified as - one of the following: 'clientside','serverside','c', or 's'\n\n") - return('Please respecify') + .abortInvalidChoice("source.times", c("clientside", "serverside", "c", "s")) } @@ -198,9 +189,7 @@ if(source.each=='s')source.each<-'serverside' #Check that source has been specified if(source.length.out!="serverside"&&source.length.out!="clientside"&&!is.null(source.length.out)) { - message(" FAILED: if source.length.out is non-null it must be specified as - one of the following: 'clientside','serverside','c', or 's'\n\n") - return('Please respecify') + .abortInvalidChoice("source.length.out", c("clientside", "serverside", "c", "s")) } @@ -233,9 +222,7 @@ if(source.each=='s')source.each<-'serverside' #Check that source has been specified if(source.each!="serverside"&&source.each!="clientside"&&!is.null(source.each)) { - message(" FAILED: if source.each is non-null it must be specified as - one of the following: 'clientside','serverside','c', or 's'\n\n") - return('Please respecify') + .abortInvalidChoice("source.each", c("clientside", "serverside", "c", "s")) } diff --git a/R/ds.replaceNA.R b/R/ds.replaceNA.R index 1ec2d3a9f..bd21cbbaf 100644 --- a/R/ds.replaceNA.R +++ b/R/ds.replaceNA.R @@ -92,19 +92,15 @@ #' ds.replaceNA <- function(x=NULL, forNA=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of a vector!", call.=FALSE) - } + .checkArgProvided(x, "the name of a vector") # check if replacement values have been provided - if(is.null(forNA)){ - stop("Please provide a list of replacement values!", call.=FALSE) - }else{ - if(length(forNA) != length(datasources)){ - stop("'forNA' must be of the same length as the number of datasources/studies!", call.=FALSE) - } + .checkArgProvided(forNA, "a list of replacement values") + if(length(forNA) != length(datasources)){ + supplied <- .describeSupplied(forNA) # nolint: object_usage_linter. Used in the cli template + cli_abort(c("{.arg forNA} must have one element per study.", "x" = "{.arg forNA} is {supplied}, which has {length(forNA)} element{?s} for {length(datasources)} stud{?y/ies}.")) } for(i in 1:length(datasources)){ @@ -114,18 +110,16 @@ ds.replaceNA <- function(x=NULL, forNA=NULL, newobj=NULL, datasources=NULL){ cally <- call("numNaDS", x) numNAs <- DSI::datashield.aggregate(datasources[i], cally) if(length(forNA[[i]]) != 1 & length(forNA[[i]]) != numNAs[[1]]$numNA){ - message("The number of replacement values must be of length 1 or of the same length as the number of missing values.") - stop(paste0("This is not the case in ", names(datasources)[i]), call.=FALSE) + supplied <- .describeSupplied(forNA[[i]]) + cli_abort(c("Replacement values must have length 1 or match the number of missing values.", "i" = "{.val {names(datasources)[i]}} has {numNAs[[1]]$numNA} missing value{?s}.", "x" = "{.arg forNA} gives {supplied} for it.")) } } - if(is.null(newobj)){ - newobj <- "replacena.newobj" - } + newobj <- .resolveNewobjName(newobj, "replacena.newobj") # call the server side function and doo the replacement for each server for(i in 1:length(datasources)){ - message(paste0("--Processing ", names(datasources)[i], "...")) + cli_inform("Processing {.val {names(datasources)[i]}}...") cally <- call("replaceNaDS", x, forNA[[i]]) DSI::datashield.assign(datasources[i], newobj, cally) diff --git a/R/ds.rm.R b/R/ds.rm.R index 9e104228a..e923aec30 100644 --- a/R/ds.rm.R +++ b/R/ds.rm.R @@ -69,11 +69,9 @@ ds.rm<-function(x.names=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if (is.null(x.names)) { - stop("Please provide the names of the objects to be deleted (eg 'object.name') as the x.names argument", call.=FALSE) - } + .checkArgProvided(x.names, "the names of the objects to delete") #make transmittable via parser x.names.transmit <- paste(x.names,collapse=",") diff --git a/R/ds.rowColCalc.R b/R/ds.rowColCalc.R index 7aecbba04..ed792283b 100644 --- a/R/ds.rowColCalc.R +++ b/R/ds.rowColCalc.R @@ -68,20 +68,16 @@ #' ds.rowColCalc <- function(x=NULL, operation=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of a data.frame or matrix!", call.=FALSE) - } + .checkArgProvided(x, "the name of a data.frame or matrix") ops <- c("rowSums","colSums","rowMeans","colMeans") if(is.null(operation)){ - message(" ALERT!") - message(" Please indicate the calculation required.") - stop("'operation' = NULL. Please set it to 'rowSums', 'colSums', 'rowMeans' or 'colMeans'", call.=FALSE) + cli_abort("{.arg operation} must be {.or {.val {ops}}}, not {.code NULL}.") }else{ if(!any(operation %in% ops)){ - stop("'operation' must be set to: 'rowSums', 'colSums', 'rowMeans' or 'colMeans'") + .abortInvalidChoice("operation", ops) } } @@ -89,9 +85,7 @@ ds.rowColCalc <- function(x=NULL, operation=NULL, newobj=NULL, datasources=NULL) indx <- which(ops == operation) # create a name by default if user did not provide a name for the new variable - if(is.null(newobj)){ - newobj <- "rowcolcalc.newobj" - } + newobj <- .resolveNewobjName(newobj, "rowcolcalc.newobj") # call the server side function that does the job DSI::datashield.assign(datasources, newobj, call("rowColCalcDS", dataset.name=x, operation=indx)) diff --git a/R/ds.sample.R b/R/ds.sample.R index 9128a9e18..cb67fd100 100644 --- a/R/ds.sample.R +++ b/R/ds.sample.R @@ -130,44 +130,24 @@ ds.sample<-function(x=NULL, size=NULL, seed.as.integer=NULL, replace=FALSE, prob = NULL, newobj=NULL,datasources=NULL, notify.of.progress=FALSE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if a value has been provided for x - if(is.null(x)){ - return("Error: x must denote a character string naming the serverside object to be sampled or an integer N denoting permute 1:N") - } + .checkArgProvided(x, "a character string that names a server-side object, or an integer N to permute 1:N") # check if a valid value has been provided for size if x denotes a vector, # matrix or data.frame on the serverside if(is.character(x)&&is.null(size)){ - return("Error: size must have a value which is an integer denoting how many records to be sampled") + cli_abort("{.arg size} must be an integer that sets how many records to sample, not {.code NULL}.") } # if no value specified for output object, then specify a default - if(is.null(newobj)) - { - newobj <- "newobj.sample" - } + newobj <- .resolveNewobjName(newobj, "newobj.sample") ######################## #TEST SEED PRIMING VALUE -seed.valid<-0 - -if(is.null(seed.as.integer)){ -seed.as.text<-"NULL" -seed.valid<-1 -} - -if(is.numeric(seed.as.integer)){ -seed.as.text<-as.character(seed.as.integer) -seed.valid<-1 -} - -if(seed.valid==0){ -mess1<-("ERROR failed: seed.as.integer must be set as an integer [numeric] or left NULL") -return(mess1) -} +seed.as.text <- .seedAsText(seed.as.integer) ############################################################# #SET SEED IN EACH STUDY AS IN PSEUDORANDOM NUMBER GENERATORS @@ -194,16 +174,14 @@ single.integer.seed<-c(single.integer.seed,seed.as.integer.study.specific) if(seed.as.text=="NULL"){ if (notify.of.progress) - message("NO SEED SET IN STUDY",study.id,"\n\n") + cli_inform("No seed set in {.val {names(datasources)[study.id]}}.") } if (notify.of.progress) - message("setSeedDS(", seed.as.text, ")") + cli_inform("Setting seed {seed.as.text} in {.val {names(datasources)[study.id]}}.") ssDS.obj[[study.id]] <- datashield.aggregate(datasources[study.id], call("setSeedDS", seedtext=seed.as.text)) } -if (notify.of.progress) - message("\n\n") diff --git a/R/ds.scatterPlot.R b/R/ds.scatterPlot.R index 6a76d7986..11a0a7248 100644 --- a/R/ds.scatterPlot.R +++ b/R/ds.scatterPlot.R @@ -131,15 +131,11 @@ #' ds.scatterPlot <- function(x=NULL, y=NULL, method='deterministic', k=3, noise=0.25, type="split", return.coords=FALSE, datasources=NULL, classConsistencyCheck=FALSE){ - if(is.null(x)){ - stop("Please provide the name of the x-variable", call.=FALSE) - } + .checkArgProvided(x, "the name of the x variable") - if(is.null(y)){ - stop("Please provide the name of the y-variable", call.=FALSE) - } + .checkArgProvided(y, "the name of the y variable") - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # Save par and setup reseting of par values old_par <- graphics::par(no.readonly = TRUE) @@ -163,8 +159,8 @@ ds.scatterPlot <- function(x=NULL, y=NULL, method='deterministic', k=3, noise=0. # call the server-side function that generates the x and y coordinates of the centroids output <- datashield.aggregate(datasources, call("scatterPlotDS", x.name=x, y.name=y, method.indicator=method.indicator, k=k, noise=noise)) if(classConsistencyCheck){ - .checkClassConsistency(output, field = "class.x", object_name = x) - .checkClassConsistency(output, field = "class.y", object_name = y) + .checkClassConsistency(output, field = "class.x", objectName = x) + .checkClassConsistency(output, field = "class.y", objectName = y) } pooled.points.x <- c() @@ -214,7 +210,7 @@ ds.scatterPlot <- function(x=NULL, y=NULL, method='deterministic', k=3, noise=0. return(message=return.message) } }else{ - stop('Function argument "type" has to be either "combine" or "split"') + .abortInvalidChoice("type", c("combine", "split")) } } } diff --git a/R/ds.seq.R b/R/ds.seq.R index 13fc644a4..0e597b254 100644 --- a/R/ds.seq.R +++ b/R/ds.seq.R @@ -117,7 +117,7 @@ ds.seq<-function(FROM.value.char = "1", BY.value.char = "1", TO.value.char=NULL, LENGTH.OUT.value.char = NULL, ALONG.WITH.name=NULL, newobj="newObj", datasources=NULL) { ###datasources - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) ###FROM.value.char # check FROM.value.char is valid @@ -127,7 +127,8 @@ ds.seq<-function(FROM.value.char = "1", BY.value.char = "1", TO.value.char=NULL, if(!is.numeric(eval(parse(text=FROM.value.char))))FROM.valid<-0 } if(!FROM.valid){ - return("Error: If FROM.value.char is non.NULL, it must be a real number in inverted commas eg '-3.7' or '0'") + supplied <- .describeSupplied(FROM.value.char) # nolint: object_usage_linter. Used in the cli template + cli_abort(c("{.arg FROM.value.char} must be a real number in inverted commas, not {supplied}.", "i" = "For example, {.val -3.7} or {.val 0}.")) } ###TO.value.char @@ -138,7 +139,8 @@ ds.seq<-function(FROM.value.char = "1", BY.value.char = "1", TO.value.char=NULL, if(!is.numeric(eval(parse(text=TO.value.char))))TO.valid<-0 } if(!TO.valid){ - return("Error: If TO.value.char is non.NULL, it must be a real number in inverted commas eg '-3.7' or '0'") + supplied <- .describeSupplied(TO.value.char) + cli_abort(c("{.arg TO.value.char} must be a real number in inverted commas, not {supplied}.", "i" = "For example, {.val -3.7} or {.val 0}.")) } ###BY.value.char @@ -149,7 +151,8 @@ ds.seq<-function(FROM.value.char = "1", BY.value.char = "1", TO.value.char=NULL, if(!is.numeric(eval(parse(text=BY.value.char))))BY.valid<-0 } if(!BY.valid){ - return("Error: If FROM.value.char is non.NULL, it must be a real number in inverted commas eg '5' or '-98.7321'") + supplied <- .describeSupplied(BY.value.char) + cli_abort(c("{.arg BY.value.char} must be a real number in inverted commas, not {supplied}.", "i" = "For example, {.val 5} or {.val -98.7321}.")) } ###LENGTH.OUT.value.char @@ -160,19 +163,21 @@ ds.seq<-function(FROM.value.char = "1", BY.value.char = "1", TO.value.char=NULL, if(!is.numeric(eval(parse(text=LENGTH.OUT.value.char))))LENGTH.OUT.valid<-0 } if(!LENGTH.OUT.valid){ - return("Error: If LENGTH.OUT.value.char is non.NULL, it must be an integer in inverted commas eg '87187'") + supplied <- .describeSupplied(LENGTH.OUT.value.char) + cli_abort(c("{.arg LENGTH.OUT.value.char} must be an integer in inverted commas, not {supplied}.", "i" = "For example, {.val 87187}.")) } ###ALONG.WITH.name # check if user has correctly provided the name of a column to hold ALONG.WITH.name if(!(is.null(ALONG.WITH.name) || is.character(ALONG.WITH.name))){ - return("Error: If ALONG.WITH.name is non.NULL, it must specify the name of a serverside vector in inverted commas") + supplied <- .describeSupplied(ALONG.WITH.name) + cli_abort("{.arg ALONG.WITH.name} must be the name of a server-side vector in inverted commas, not {supplied}.") } ###Either LENGTH.OUT.value.char or ALONG.WITH.name must be non-NULL if(is.null(TO.value.char)&&is.null(LENGTH.OUT.value.char)&&is.null(ALONG.WITH.name)){ - return("Error: Either TO.value.char or LENGTH.OUT.value.char or ALONG.WITH.name must be non-NULL, they cannot both be NULL") + cli_abort("One of {.arg TO.value.char}, {.arg LENGTH.OUT.value.char} or {.arg ALONG.WITH.name} must be set.") } diff --git a/R/ds.setSeed.R b/R/ds.setSeed.R index 5192f7536..e14b275fa 100644 --- a/R/ds.setSeed.R +++ b/R/ds.setSeed.R @@ -87,26 +87,10 @@ #' @export ds.setSeed<-function(seed.as.integer=NULL,datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) -seed.valid<-0 - -if(is.null(seed.as.integer)){ -seed.as.text<-"NULL" -seed.valid<-1 -} - -if(is.numeric(seed.as.integer)){ -seed.as.text<-as.character(seed.as.integer) -seed.valid<-1 -} - - -if(seed.valid==0){ -mess1<-("ERROR terminated: seed.as.integer must be set as an integer [numeric] or as being NULL") -return(mess1) -} +seed.as.text <- .seedAsText(seed.as.integer) ssDS.obj <- datashield.aggregate(datasources, call("setSeedDS", seedtext=seed.as.text)) diff --git a/R/ds.skewness.R b/R/ds.skewness.R index 52f0c87a9..46e3b1d9f 100644 --- a/R/ds.skewness.R +++ b/R/ds.skewness.R @@ -81,14 +81,12 @@ #' ds.skewness <- function(x=NULL, method=1, type='both', datasources=NULL, classConsistencyCheck=FALSE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input vector") if(!all(method %in% c(1,2,3))){ - stop("method must be an integer between 1 and 3", call.=FALSE) + cli_abort("{.arg method} must be {.or {.val {1:3}}}, not {.val {method}}.") } # enable valid aliases for "type" argument @@ -96,7 +94,7 @@ ds.skewness <- function(x=NULL, method=1, type='both', datasources=NULL, classCo if(type == 'split' | type == 'splits' | type == 's') type <- 'split' if(type == 'both' | type == 'b' ) type <- 'both' if(type != 'combine' & type != 'split' & type != 'both') - stop('Function argument "type" has to be either "both", "combine" or "split"', call.=FALSE) + .abortInvalidChoice("type", c("both", "combine", "split")) if (type=='split' | type=='both'){ calltext.split <- call("skewnessDS1", x, method) @@ -116,7 +114,7 @@ ds.skewness <- function(x=NULL, method=1, type='both', datasources=NULL, classCo #global.var <- ds.var(x, type='combine')$Global.Variance[,'EstimatedVar'] if (is.na(global.mean)){ - stop("FAILED: The number of valid observations in one or more studies is less than nfilter.tab. \n Check that by using the argument type=='split'", call.=FALSE) + cli_abort(c("The number of valid observations in at least one study is less than {.code nfilter.tab}.", "i" = "Use {.code type = \"split\"} to check each study.")) }else{ calltext.combined <- call("skewnessDS2", x, global.mean) output.combined <- DSI::datashield.aggregate(datasources, calltext.combined) diff --git a/R/ds.sqrt.R b/R/ds.sqrt.R index 76a7538ec..376fa212a 100644 --- a/R/ds.sqrt.R +++ b/R/ds.sqrt.R @@ -71,15 +71,11 @@ #' ds.sqrt <- function(x=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input object!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input object") - if(is.null(newobj)){ - newobj <- "sqrt.newobj" - } + newobj <- .resolveNewobjName(newobj, "sqrt.newobj") cally <- call("sqrtDS", x) DSI::datashield.assign(datasources, newobj, cally) diff --git a/R/ds.summary.R b/R/ds.summary.R index bac5cb62b..ea3f2080f 100644 --- a/R/ds.summary.R +++ b/R/ds.summary.R @@ -67,11 +67,9 @@ #' ds.summary <- function(x=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input vector") # check the type of x to drive client-side dispatch typ <- checkClass(datasources, x) @@ -79,7 +77,8 @@ ds.summary <- function(x=NULL, datasources=NULL){ # the input object must be a numeric or an integer vector # the input object must be a dataframe or a factor if(!('data.frame' %in% typ) & !('character' %in% typ) & !('factor' %in% typ) & !('integer' %in% typ) & !('list' %in% typ) & !('logical' %in% typ) & !('matrix' %in% typ) & !('numeric' %in% typ)){ - stop("The input object must be a 'data.frame', 'character', factor', 'integer', 'list', 'logical', 'matrix' or 'numeric'.", call.=FALSE) + allowedClasses <- vapply(c("data.frame", "character", "factor", "integer", "list", "logical", "matrix", "numeric"), function(x) cli::format_inline("{.cls {x}}"), character(1)) # nolint: object_usage_linter. Used in the cli template + cli_abort("{.arg x} must be of class {.or {allowedClasses}}, not {.cls {typ}}.") } stdnames <- names(datasources) diff --git a/R/ds.table.R b/R/ds.table.R index 328925aaa..75c4d8631 100644 --- a/R/ds.table.R +++ b/R/ds.table.R @@ -191,27 +191,28 @@ ds.table <- function(rvar=NULL, cvar=NULL, stvar=NULL, report.chisq.tests=FALSE, table.assign=FALSE, newobj=NULL, datasources=NULL, force.nfilter=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) # check if a value has been provided for rvar - if(is.null(rvar)){ - return("Error: rvar must have a value which is a character string naming the row variable for the table") - } + .checkArgProvided(rvar, "a character string that names the row variable") if(!is.null(cvar)&&!is.character(cvar)){ - return("Error: if cvar is not null, it must have a value which is a character string naming the column variable for the table") + supplied <- .describeSupplied(cvar) # nolint: object_usage_linter. Used in the cli template + cli_abort("{.arg cvar} must be a character string that names the column variable, not {supplied}.") } if(!is.null(stvar)&&!is.character(stvar)){ - return("Error: if stvar is not null, it must have a value which is a character string naming the variable coding separate tables for the table") + supplied <- .describeSupplied(stvar) + cli_abort("{.arg stvar} must be a character string that names the variable that codes the separate tables, not {supplied}.") } if(useNA!="no" && useNA!="always"){ - stop("useNA must be either 'no' or 'always'.") + .abortInvalidChoice("useNA", c("no", "always")) } if(!is.null(force.nfilter)&&!is.character(force.nfilter)){ - return("Error: if force.nfilter is not null, it must have a value which is a character string specifying an integer for the forced value of the nfilter") + supplied <- .describeSupplied(force.nfilter) + cli_abort("{.arg force.nfilter} must be a character string that specifies an integer, not {supplied}.") } @@ -272,7 +273,7 @@ ds.table <- function(rvar=NULL, cvar=NULL, stvar=NULL, report.chisq.tests=FALSE, } if (length(rvar.all.levels.all.studies) == 0) { - stop(paste0("Unable to obtain factors for rvar: '", rvar , "'"), call. = FALSE) + cli_abort("Can't obtain factors for {.arg rvar}, {.val {rvar}}.") } rvar.all.unique.levels <- as.character(unique(rvar.all.levels.all.studies)) @@ -294,7 +295,7 @@ ds.table <- function(rvar=NULL, cvar=NULL, stvar=NULL, report.chisq.tests=FALSE, } if (length(cvar.all.levels.all.studies) == 0) { - stop(paste0("Unable to obtain factors for cvar: '", cvar , "'"), call. = FALSE) + cli_abort("Can't obtain factors for {.arg cvar}, {.val {cvar}}.") } cvar.all.unique.levels <- as.character(unique(cvar.all.levels.all.studies)) @@ -318,7 +319,7 @@ ds.table <- function(rvar=NULL, cvar=NULL, stvar=NULL, report.chisq.tests=FALSE, } if (length(stvar.all.levels.all.studies) == 0) { - stop(paste0("Unable to obtain factors for stvar: '", stvar , "'"), call. = FALSE) + cli_abort("Can't obtain factors for {.arg stvar}, {.val {stvar}}.") } stvar.all.unique.levels <- as.character(unique(stvar.all.levels.all.studies)) @@ -332,10 +333,7 @@ ds.table <- function(rvar=NULL, cvar=NULL, stvar=NULL, report.chisq.tests=FALSE, if(table.assign) { - if(is.null(newobj)) - { - newobj<-"table.newobj" - } + newobj <- .resolveNewobjName(newobj, "table.newobj") # CALL THE MAIN SERVER SIDE ASSIGN FUNCTION @@ -405,14 +403,8 @@ if(num.valid.studies==0) { if ((! table.assign) || report.chisq.tests) { - validity.message<-"All studies failed for reasons identified below" - message("\n",validity.message,"\n\n") - for(ns in 1:numsources.orig) - { - message("\nStudy",ns,": ",error.messages[[ns]],"\n") - } - - return(list(validity.message=validity.message,error.messages=error.messages)) + failures <- paste0(names(error.messages), ": ", unlist(error.messages)) # nolint: object_usage_linter. + cli_abort(c("All studies failed.", "x" = "{failures}")) } else { @@ -474,12 +466,11 @@ if(num.valid.studies==numsources.orig) validity.message<-"Data in all studies were valid" if (! table.assign) { - message("\n",validity.message,"\n") + cli_inform("{validity.message}") for(ns in 1:numsources.orig) { - message("\nStudy",ns,": ",error.messages[[ns]]) + cli_inform("{.val {names(error.messages)[ns]}}: {error.messages[[ns]]}") } - message("\n\n") } } @@ -501,8 +492,9 @@ if(numsources>1) if(table.dimensions[ns]!=table.dimensions[ns+1]) { all.dims.same<-FALSE - return.message<-"Warning: tables in different sources have different numbers of dimensions. Please analyse and combine yourself from study.specific tables above" - return(return.message) + dims <- paste0(vapply(study.names.valid, function(study) cli::format_inline("{.val {study}}"), character(1)), " has ", table.dimensions, " dimensions.") + names(dims) <- rep("x", length(dims)) + cli_abort(c("Tables in different sources have different numbers of dimensions.", dims, "i" ="Analyse and combine them yourself from the study-specific tables.")) } } @@ -718,9 +710,7 @@ for(oo in 1:length(table.current.study[,1])) if(d1.a!=d1||d2.a!=d2||d3.a!=d3) { - return.message= "Dimensions of tables not behaving sensibly across studies.Please check the data in each study and calculate counts and percentages, yourself, using the counts from the individual studies" - message(return.message) - return(return.message) + cli_abort(c("Table dimensions differ across studies.", "x" = "Cell {.arg rvar} = {.val {d1}}, {.arg cvar} = {.val {d2}}, {.arg stvar} = {.val {d3}} in {.val {study.names.valid[ns]}} doesn't match the combined table.", "i" = "Check the data in each study and calculate counts and percentages yourself from the counts in each study.")) } #dimension markers match so allocate count to correct cell @@ -939,9 +929,7 @@ for(oo in 1:length(table.current.study[,1])) if(d1.a!=d1||d2.a!=d2) { - return.message= "Dimensions of tables not behaving sensibly across studies.Please check the data in each study and calculate counts and percentages, yourself, using the counts from the individual studies" - message(return.message) - return(return.message) + cli_abort(c("Table dimensions differ across studies.", "x" = "Cell {.arg rvar} = {.val {d1}}, {.arg cvar} = {.val {d2}} in {.val {study.names.valid[ns]}} doesn't match the combined table.", "i" = "Check the data in each study and calculate counts and percentages yourself from the counts in each study.")) } #dimension markers match so allocate count to correct cell @@ -1133,9 +1121,7 @@ for(oo in 1:length(table.current.study[,1])) if(d1.a!=d1) { - return.message= "Dimensions of tables not behaving sensibly across studies.Please check the data in each study and calculate counts and percentages, yourself, using the counts from the individual studies" - message(return.message) - return(return.message) + cli_abort(c("Table dimensions differ across studies.", "x" = "Cell {.arg rvar} = {.val {d1}} in {.val {study.names.valid[ns]}} doesn't match the combined table.", "i" = "Check the data in each study and calculate counts and percentages yourself from the counts in each study.")) } #dimension markers match so allocate count to correct cell diff --git a/R/ds.tapply.R b/R/ds.tapply.R index 5342c3323..b7c842dcc 100644 --- a/R/ds.tapply.R +++ b/R/ds.tapply.R @@ -125,26 +125,21 @@ ds.tapply <- function(X.name=NULL, INDEX.names=NULL, FUN.name=NULL, datasources=NULL){ ###datasources - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) ###X.name # check if user has provided the name of the column that holds X.name - if(is.null(X.name)){ - return("Error: Please provide the name of the variable to be summarized, as a character string") - } + .checkArgProvided(X.name, "the name of the variable to summarise, as a character string") ###INDEX.names # check if user has provided the name of the column(s) that holds INDEX.names if(is.null(INDEX.names)){ - Err.1 <- "Error: Please provide the name of the single factor or" - Err.2 <- "the list of factors to index the variable to be summarized." - Err.3 <- "In either case the argument must be specified in inverted commas" - return(list(Error.message=Err.1, Err.cont2=Err.2, Err.cont3=Err.3)) + cli_abort("{.arg INDEX.names} must name a single factor or a list of factors, in inverted commas, not {.code NULL}.") } # check if the vector or list of INDEX.names includes up to two names if(length(INDEX.names) > 2){ - stop("The 'INDEX.names' can include the names of up to two factors", call.=FALSE) + cli_abort(c("{.arg INDEX.names} must name no more than two factors.", "x" = "{.arg INDEX.names} is {.val {unlist(INDEX.names)}}.")) } # make INDEX.names transmitable @@ -156,9 +151,7 @@ ds.tapply <- function(X.name=NULL, INDEX.names=NULL, FUN.name=NULL, datasources= ###FUN.name # check if user has provided a valid summarizing function - if(is.null(FUN.name)){ - return("Error: Please provide a valid summarizing function, as a character string") - } + .checkArgProvided(FUN.name, "a valid summarising function, as a character string") # CALL THE PRIMARY SERVER SIDE FUNCTION calltext <- call("tapplyDS", X.name, INDEX.names.transmit, FUN.name) diff --git a/R/ds.tapply.assign.R b/R/ds.tapply.assign.R index 14722a942..d799f1355 100644 --- a/R/ds.tapply.assign.R +++ b/R/ds.tapply.assign.R @@ -130,26 +130,21 @@ ds.tapply.assign <- function(X.name=NULL, INDEX.names=NULL, FUN.name=NULL, newobj=NULL, datasources=NULL){ ###datasources - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) ###X.name # check if user has provided the name of the column that holds X.name - if(is.null(X.name)){ - return("Error: Please provide the name of the variable to be summarized, as a character string") - } + .checkArgProvided(X.name, "the name of the variable to summarise, as a character string") ###INDEX.names # check if user has provided the name of the column(s) that holds INDEX.names if(is.null(INDEX.names)){ - Err.1 <- "Error: Please provide the name of the single factor or" - Err.2 <- "the list of factors to index the variable to be summarized." - Err.3 <- "In either case the argument must be specified in inverted commas" - return(list(Error.message=Err.1, Err.cont2=Err.2, Err.cont3=Err.3)) + cli_abort("{.arg INDEX.names} must name a single factor or a list of factors, in inverted commas, not {.code NULL}.") } # check if the vector or list of INDEX.names includes up to two names if(length(INDEX.names) > 2){ - stop("The 'INDEX.names' can include the names of up to two factors", call.=FALSE) + cli_abort(c("{.arg INDEX.names} must name no more than two factors.", "x" = "{.arg INDEX.names} is {.val {unlist(INDEX.names)}}.")) } # make INDEX.names transmitable @@ -161,14 +156,10 @@ ds.tapply.assign <- function(X.name=NULL, INDEX.names=NULL, FUN.name=NULL, newob ###FUN.name # check if user has provided a valid summarizing function - if(is.null(FUN.name)){ - return("Error: Please provide a valid summarizing function, as a character string") - } + .checkArgProvided(FUN.name, "a valid summarising function, as a character string") # create a name by default if user did not provide a name for the new tapply object - if(is.null(newobj)){ - newobj <- "tapply.assign.newobj" - } + newobj <- .resolveNewobjName(newobj, "tapply.assign.newobj") # CALL THE PRIMARY SERVER SIDE FUNCTION calltext <- call("tapplyDS.assign", X.name, INDEX.names.transmit, FUN.name) diff --git a/R/ds.unList.R b/R/ds.unList.R index 6f98fdddc..3df4dd01b 100644 --- a/R/ds.unList.R +++ b/R/ds.unList.R @@ -70,17 +70,13 @@ #' @export ds.unList <- function(x.name=NULL, newobj=NULL, datasources=NULL){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x.name)){ - stop("Please provide the name of the input vector!", call.=FALSE) - } + .checkArgProvided(x.name, "the name of the input vector") # create a name by default if user did not provide a name for the new variable - if(is.null(newobj)){ - newobj <- "unlist.newobj" - } + newobj <- .resolveNewobjName(newobj, "unlist.newobj") # call the server side function calltext <- call("unListDS", x.name) diff --git a/R/ds.unique.R b/R/ds.unique.R index 07ceced2f..4c09b74fd 100644 --- a/R/ds.unique.R +++ b/R/ds.unique.R @@ -48,15 +48,11 @@ #' ds.unique <- function(x.name = NULL, newobj = NULL, datasources = NULL) { - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if (is.null(x.name)) { - stop("x.name=NULL. Please provide the names of the objects to de-duplicated!", call. = FALSE) - } + .checkArgProvided(x.name, "the names of the objects to de-duplicate") - if (is.null(newobj)) { - newobj <- "unique.newobj" - } + newobj <- .resolveNewobjName(newobj, "unique.newobj") cally <- call('uniqueDS', x.name) DSI::datashield.assign(datasources, newobj, cally) diff --git a/R/ds.var.R b/R/ds.var.R index 4247e024b..4266f57ef 100644 --- a/R/ds.var.R +++ b/R/ds.var.R @@ -75,11 +75,9 @@ #' ds.var <- function(x=NULL, type='split', datasources=NULL, classConsistencyCheck=FALSE){ - datasources <- .set_datasources(datasources) + datasources <- .resolveDatasources(datasources) - if(is.null(x)){ - stop("Please provide the name of the input object!", call.=FALSE) - } + .checkArgProvided(x, "the name of the input object") ################################################################################################### #MODULE: EXTEND "type" argument to include "both" and enable valid alisases # diff --git a/R/glmChecks.R b/R/glmChecks.R index 2610a6309..b73ef11d8 100644 --- a/R/glmChecks.R +++ b/R/glmChecks.R @@ -14,12 +14,13 @@ #' process. Should be NULL or a numeric vector. #' @param datasources a list of \code{\link[DSI]{DSConnection-class}} objects obtained after login. If the #' the default set of connections will be used: see \link[DSI]{datashield.connections_default}. +#' @param call The frame to report the error from. #' @keywords internal #' @return an integer 0 if check was passed and 1 if failed #' @author Gaye, A. #' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands #' -glmChecks <- function(formula, data, offset, weights, datasources){ +glmChecks <- function(formula, data, offset, weights, datasources, call=parent.frame()){ # turn the formula into a character formula <- paste0(Reduce(paste, deparse(formula))) @@ -57,7 +58,7 @@ glmChecks <- function(formula, data, offset, weights, datasources){ stdnames <- names(datasources) for(i in 1:length(elts)){ if(is.na(suppressWarnings(as.numeric(elts[i])))){ # making sure an eventual intercept term is not included in the checks - message(paste0(" ", elts[i], "...")) + cli_inform("{elts[i]}...") for(j in 1: length(datasources)){ # check if the variable is defined on the server site myterms <- unlist(strsplit(elts[i], split='$', fixed=TRUE)) @@ -65,15 +66,15 @@ glmChecks <- function(formula, data, offset, weights, datasources){ cally <- call("exists", myterms[1]) out <- DSI::datashield.aggregate(datasources[j], cally) if(!(out[[1]])){ - stop(paste0("'", myterms[1], "' is not defined in ", stdnames[j], "!"), call.=FALSE) + cli_abort("{.val {myterms[1]}} isn't defined in {.val {stdnames[j]}}.", call = call) }else{ cally <- call("colnamesDS", myterms[1]) clnames <- unlist(DSI::datashield.aggregate(datasources[j], cally)) if(!(myterms[2] %in% clnames)){ - stop(paste0("'", myterms[2], "' is not defined in ", stdnames[j], "!"), call.=FALSE) + cli_abort("{.val {myterms[2]}} isn't defined in {.val {stdnames[j]}}.", call = call) }else{ call0 <- call("isNaDS", elts[i]) - if(varIdentifier[i] == "offset" | varIdentifier[i] == "weights"){ typ <- checkClass(datasources, elts[i]) } + if(varIdentifier[i] == "offset" || varIdentifier[i] == "weights"){ typ <- checkClass(datasources, elts[i], call = call) } if(varIdentifier[i] == "weights"){ call1 <- paste0("checkNegValueDS(", elts[i], ")") } } } @@ -82,37 +83,37 @@ glmChecks <- function(formula, data, offset, weights, datasources){ cally <- call("colnamesDS", data) clnames <- unlist(DSI::datashield.aggregate(datasources[j], cally)) if(!(elts[i] %in% clnames)){ - dd <- isDefined(datasources, elts[i]) + isDefined(datasources, elts[i], call = call) call0 <- call("isNaDS", elts[i]) - if(varIdentifier[i] == "offset" | varIdentifier[i] == "weights"){ typ <- checkClass(datasources, elts[i]) } + if(varIdentifier[i] == "offset" || varIdentifier[i] == "weights"){ typ <- checkClass(datasources, elts[i], call = call) } if(varIdentifier[i] == "weights"){ call1 <- paste0("checkNegValueDS(", elts[i], ")") } }else{ call0 <- call("isNaDS", paste0(data, "$", elts[i])) - if(varIdentifier[i] == "offset" | varIdentifier[i] == "weights"){ typ <- checkClass(datasources, paste0(data, "$", elts[i])) } + if(varIdentifier[i] == "offset" || varIdentifier[i] == "weights"){ typ <- checkClass(datasources, paste0(data, "$", elts[i]), call = call) } if(varIdentifier[i] == "weights"){ call1 <- paste0("checkNegValueDS(", paste0(data, "$", elts[i]), ")") } } }else{ - defined <- isDefined(datasources, elts[i]) + isDefined(datasources, elts[i], call = call) call0 <- call("isNaDS", elts[i]) - if(varIdentifier[i] == "offset" | varIdentifier[i] == "weights"){ typ <- checkClass(datasources, elts[i]) } + if(varIdentifier[i] == "offset" || varIdentifier[i] == "weights"){ typ <- checkClass(datasources, elts[i], call = call) } if(varIdentifier[i] == "weights"){ call1 <- paste0("checkNegValueDS(", elts[i], ")") } } } # check if variable is not missing at complete out1 <- DSI::datashield.aggregate(datasources[j], call0) if(out1[[1]]$is.na){ - stop("The variable ", elts[i], " in ", stdnames[j], " is missing at complete (all values are 'NA').", call.=FALSE) + cli_abort("{.val {elts[i]}} has only missing values in {.val {stdnames[j]}}.", call = call) } # if offset and or weights are set check they are numeric and for weights that it does not hold negative value if(varIdentifier[i] == "offset" | varIdentifier[i] == "weights"){ if(!('numeric' %in% typ)){ - stop(paste0("'", elts[i], "' ", "is not a numeric in ", stdnames[j]), call.=FALSE) + cli_abort("{.val {elts[i]}} must be {.cls numeric} in {.val {stdnames[j]}}, not {.cls {typ}}.", call = call) } } if(varIdentifier[i] == "weights"){ checkres <- unlist(DSI::datashield.aggregate(datasources[j], as.symbol(call1))) if(checkres){ - stop(paste0("Negative weights not allowed - check study ", stdnames[j], "!"), call.=FALSE) + cli_abort("Weights {.val {elts[i]}} must not be negative in {.val {stdnames[j]}}.", call = call) } } diff --git a/R/isDefined.R b/R/isDefined.R index 621b809a8..126ebbacf 100644 --- a/R/isDefined.R +++ b/R/isDefined.R @@ -14,9 +14,10 @@ #' @return returns an error message if \code{error.message} argument is set to TRUE (default) #' and if the input object is not defined in one or more studies, or a Boolean value if #' \code{error.message} argument is set to FALSE. +#' @param call The frame to report the error from. #' @author Demetris Avraam for DataSHIELD Development Team #' -isDefined <- function(datasources=NULL, obj=NULL, error.message=TRUE){ +isDefined <- function(datasources=NULL, obj=NULL, error.message=TRUE, call=parent.frame()){ inputobj <- unlist(obj) @@ -34,7 +35,7 @@ isDefined <- function(datasources=NULL, obj=NULL, error.message=TRUE){ } if(error.message==TRUE & any(out==FALSE)){ - stop("The input object ", inputobj[i], " is not defined in ", paste(names(which(out==FALSE)), collapse=", "), "!" , call.=FALSE) + cli_abort("{.val {inputobj[i]}} isn't defined in {.val {names(which(out==FALSE))}}.", call = call) }else{ return(out) } diff --git a/R/utils.R b/R/utils.R index db6ac35d4..e3976dfcd 100644 --- a/R/utils.R +++ b/R/utils.R @@ -6,7 +6,7 @@ #' @return A list of data sources. #' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands #' @noRd -.get_datasources <- function(datasources) { +.getDatasources <- function(datasources) { if (is.null(datasources)) { datasources <- datashield.connections_find() } @@ -16,13 +16,17 @@ #' Verify that the provided data sources are of class 'DSConnection'. #' #' @param datasources A list of data sources. +#' @param call The frame to report the error from. #' @importFrom cli cli_abort #' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands #' @noRd -.verify_datasources <- function(datasources) { - is_connection_class <- sapply(datasources, function(x) inherits(unlist(x), "DSConnection")) - if (!all(is_connection_class)) { - cli_abort("The 'datasources' were expected to be a list of DSConnection-class objects") +.verifyDatasources <- function(datasources, call = parent.frame()) { + isConnectionClass <- vapply(datasources, function(x) inherits(unlist(x), "DSConnection"), logical(1)) + if (!all(isConnectionClass)) { + bad <- which(!isConnectionClass) + supplied <- vapply(datasources[bad], .describeSupplied, character(1)) # nolint: object_usage_linter. Used in the cli template + bullets <- stats::setNames(paste0("Element ", bad, " is {supplied[", seq_along(bad), "]}."), rep("x", length(bad))) + cli_abort(c("{.arg datasources} must be a list of {.cls DSConnection} objects.", bullets), call = call) } } @@ -30,12 +34,13 @@ #' #' @param datasources An optional list of data sources. If not provided, the function will attempt #' to find available data sources. +#' @param call The frame to report the error from. #' @return A list of verified data sources. #' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands #' @noRd -.set_datasources <- function(datasources) { - datasources <- .get_datasources(datasources) - .verify_datasources(datasources) +.resolveDatasources <- function(datasources, call = parent.frame()) { + datasources <- .getDatasources(datasources) + .verifyDatasources(datasources, call = call) return(datasources) } @@ -48,20 +53,37 @@ #' @param results A named list of server-side aggregate results, one per study, #' each containing the class field named by `field`. #' @param field The name of the element holding the class. Default `"class"`. -#' @param object_name Optional name of the input object, used to make the error +#' @param objectName Optional name of the input object, used to make the error #' message specific. If `NULL` a generic message is used. +#' @param call The frame to report the error from. #' @importFrom cli cli_abort #' @return Invisibly returns `NULL`. Called for its side effect (error checking). #' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands #' @noRd -.checkClassConsistency <- function(results, field = "class", object_name = NULL) { +.checkClassConsistency <- function(results, field = "class", objectName = NULL, call = parent.frame()) { classes <- lapply(results, function(r) r[[field]]) if (length(unique(lapply(classes, sort))) > 1) { - subject <- if (is.null(object_name)) "The input object" else paste0("'", object_name, "'") - cli_abort("{subject} is not of the same class in all studies!") + if (is.null(objectName)) { + cli_abort(c("The input object must have the same class in all studies.", .describeStudyClasses(classes)), call = call) + } + cli_abort(c("{.val {objectName}} must have the same class in all studies.", .describeStudyClasses(classes)), call = call) } } +#' Describe the Class of an Object in Each Study +#' +#' @param classes A named list with the class of the object in each study. +#' @return A character vector of `cli` bullets, one per study, named `"x"`. +#' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands +#' @noRd +.describeStudyClasses <- function(classes) { + described <- vapply(classes, function(cls) cli::format_inline("{.cls {cls}}"), character(1)) + studies <- vapply(names(classes), function(study) cli::format_inline("{.val {study}}"), character(1)) + bullets <- paste0(studies, " has class ", described, ".") + names(bullets) <- rep("x", length(bullets)) + bullets +} + #' Check That a New Object Name Is Valid #' #' Internal helper that checks whether the name supplied for a server-side @@ -69,13 +91,15 @@ #' user-friendly error. #' #' @param newobj A character string naming the object to be created server-side. +#' @param call The frame to report the error from. #' @importFrom cli cli_abort #' @return Invisibly returns `NULL`. Called for its side effect (error checking). #' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands #' @noRd -.check_newobj_name <- function(newobj) { +.checkNewobjName <- function(newobj, call = parent.frame()) { if (!is.character(newobj) || length(newobj) != 1) { - cli_abort("'newobj' must be a single character string") + supplied <- .describeSupplied(newobj) # nolint: object_usage_linter. Used in the cli template + cli_abort("{.arg newobj} must be a single character string, not {supplied}.", call = call) } } @@ -88,50 +112,204 @@ #' @param newobj A character string naming the object to be created server-side, #' or `NULL` to use `default`. #' @param default The name to use when `newobj` is `NULL`. +#' @param call The frame to report the error from. #' @return A validated, single character string. #' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands #' @noRd -.set_newobj_name <- function(newobj, default) { +.resolveNewobjName <- function(newobj, default, call = parent.frame()) { if (is.null(newobj)) { newobj <- default } - .check_newobj_name(newobj) + .checkNewobjName(newobj, call = call) return(newobj) } -#' Check That a Data Frame Name Is Provided +#' Check That a Required Argument Is Provided +#' +#' Internal helper that aborts if a required argument is `NULL`, naming the +#' argument as it was passed by the calling function. +#' +#' @param x The argument to check. +#' @param description What the argument must be, e.g. "the name of the input vector". +#' @param call The frame to report the error from. +#' @importFrom cli cli_abort +#' @return Invisibly returns `NULL`. Called for its side effect (error checking). +#' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands +#' @noRd +.checkArgProvided <- function(x, description, call = parent.frame()) { + if (is.null(x)) { + cli_abort("{.arg {deparse(substitute(x))}} must be {description}, not {.code NULL}.", call = call) + } +} + +#' Check That Required Arguments Are All Set +#' +#' @param ... The arguments to check, named as the user knows them. +#' @param call The frame to report the error from. +#' @importFrom cli cli_abort +#' @return Invisibly returns `NULL`. Called for its side effect (error checking). +#' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands +#' @noRd +.checkArgsSet <- function(..., call = parent.frame()) { + values <- list(...) + unset <- names(values)[vapply(values, is.null, logical(1))] + if (length(unset) > 0) { + cli_abort(c( + "{.arg {names(values)}} must all be set.", + "x" = "{.arg {unset}} {?is/are} {.code NULL}." + ), call = call) + } +} + +#' Convert a Seed to the Text Sent to the Server +#' +#' @param seed.as.integer A number, or `NULL` for no seed. +#' @param call The frame to report the error from. +#' @importFrom cli cli_abort +#' @return The seed as a character string, or `"NULL"` when no seed was given. +#' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands +#' @noRd +.seedAsText <- function(seed.as.integer, call = parent.frame()) { + if (is.null(seed.as.integer)) { + return("NULL") + } + if (!is.numeric(seed.as.integer)) { + supplied <- .describeSupplied(seed.as.integer) # nolint: object_usage_linter. Used in the cli template + cli_abort("{.arg seed.as.integer} must be an integer or {.code NULL}, not {supplied}.", call = call) + } + return(as.character(seed.as.integer)) +} + +#' Check That a Model Formula Has No Offset or Weights Term #' -#' Internal helper that checks whether a data frame or matrix object -#' has been provided. If `NULL`, it aborts with a user-friendly error. +#' The server rejects function calls inside a formula, so an `offset()` or +#' `weights()` term always fails there. #' -#' @param df A data.frame or matrix. +#' @param formula The model formula, as a character string or formula. +#' @param call The frame to report the error from. +#' @importFrom cli cli_abort #' @return Invisibly returns `NULL`. Called for its side effect (error checking). #' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands #' @noRd -.check_df_name_provided <- function(df) { - if(is.null(df)){ - cli_abort("Please provide the name of a data.frame or matrix!") +.checkOffsetInFormula <- function(formula, call = parent.frame()) { + formulaText <- as.character(formula) + found <- unlist(regmatches(formulaText, gregexpr("\\b(offset|weights)\\s*\\([^)]*\\)", formulaText))) + if (length(found) > 0) { + cli_abort(c( + "{.arg formula} can't contain {.code offset()} or {.code weights()}.", + "x" = "Found {.code {found}}.", + "i" = "Use the {.arg offset} and {.arg weights} arguments instead." + ), call = call) + } +} + +#' Check That Each Object Has a Class That Can Be Combined +#' +#' @param datasources A list of data sources. +#' @param x The names of the server-side objects. +#' @param call The frame to report the error from. +#' @importFrom cli cli_abort +#' @return Invisibly returns `NULL`. Called for its side effect (error checking). +#' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands +#' @noRd +.checkObjectClasses <- function(datasources, x, call = parent.frame()) { + allowed <- c("data.frame", "matrix", "numeric", "integer", "character", "factor", "logical") + for (name in x) { + cls <- checkClass(datasources, name, call = call) + if (!any(allowed %in% cls)) { + allowedClasses <- vapply(allowed, function(x) cli::format_inline("{.cls {x}}"), character(1)) # nolint: object_usage_linter. Used in the cli template + cli_abort("{.val {name}} must be of class {.or {allowedClasses}}, not {.cls {cls}}.", call = call) + } + } +} + +#' Check That Objects to Be Bound Together Fit in Every Study +#' +#' Warns if column names are duplicated, and aborts if the objects differ in +#' their number of rows. +#' +#' @param datasources A list of data sources. +#' @param x The names of the server-side objects. +#' @param call The frame to report the error from. +#' @importFrom cli cli_abort cli_warn +#' @return Invisibly returns `NULL`. Called for its side effect. +#' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands +#' @noRd +.checkMultiObjectConsistency <- function(datasources, x, call = parent.frame()) { + isTable <- vapply(x, function(name) any(checkClass(datasources, name, call = call) %in% c("data.frame", "matrix")), logical(1)) + for (j in seq_along(datasources)) { + study <- datasources[j] + columns <- lapply(seq_along(x), function(i) { + if (isTable[[i]]) ds.colnames(x = x[i], datasources = study) else as.character(x[i]) + }) + if (anyDuplicated(unlist(columns)) != 0) { + cli_warn("Some column names in {.val {names(datasources)[j]}} are duplicated, so a suffix {.val .k} is added to the kth replicate.", call = call) + } + rows <- vapply(seq_along(x), function(i) { + if (isTable[[i]]) { + return(as.numeric(ds.dim(x = x[i], type = "split", datasources = study)[[1]][1])) + } + as.numeric(ds.length(x[i], type = "split", datasources = study)[[1]]) + }, numeric(1)) + if (any(rows != rows[1])) { + cli_abort(c( + "All components must have the same number of rows.", + "x" = "In {.val {names(datasources)[j]}}, {.val {x}} {?has/have} {rows} rows." + ), call = call) + } } } +#' Abort Because an Argument Is Not One of the Allowed Values +#' +#' @param argName The name of the argument, as defined in the calling function. +#' @param choices A character vector of the allowed values. +#' @param call The frame to report the error from, which also holds the argument. +#' @importFrom cli cli_abort cli_inform cli_verbatim cli_warn +#' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands +#' @noRd +.abortInvalidChoice <- function(argName, choices, call = parent.frame()) { + supplied <- .describeSupplied(get(argName, envir = call, inherits = FALSE)) # nolint: object_usage_linter. Used in the cli template + cli_abort("{.arg {argName}} must be {.or {.val {choices}}}, not {supplied}.", call = call) +} + #' Expand an Argument to One Value per Study #' #' Arguments that may differ between studies can be given either as a single #' value, used for every study, or as a vector with one value per study. #' -#' @param values A vector of length 1 or `num_studies`. -#' @param arg_name The name of the argument, used in the error message. -#' @param num_studies The number of studies being analysed. +#' @param values A vector of length 1 or `numStudies`. +#' @param argName The name of the argument, used in the error message. +#' @param numStudies The number of studies being analysed. +#' @param call The frame to report the error from. #' @importFrom cli cli_abort -#' @return A vector of length `num_studies`. +#' @return A vector of length `numStudies`. #' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands #' @noRd -.expand_to_studies <- function(values, arg_name, num_studies) { +.expandToStudies <- function(values, argName, numStudies, call = parent.frame()) { if (length(values) == 1) { - return(rep(values, num_studies)) + return(rep(values, numStudies)) } - if (length(values) != num_studies) { - cli_abort("'{arg_name}' must be length 1 or one value per study") + if (length(values) != numStudies) { + supplied <- .describeSupplied(values) # nolint: object_usage_linter. Used in the cli template + cli_abort("{.arg {argName}} must have length 1 or {numStudies} (one value per study), not {supplied}.", call = call) } return(values) } + +#' Describe a Supplied Value for an Error Message +#' +#' @param x The value the user supplied. +#' @return A string: `NULL` as code, the value if `x` is a non-empty atomic +#' vector (quoted if character), otherwise its type, such as "a list". +#' @author Tim Cadman, Genomics Coordination Centre, UMCG, Netherlands +#' @noRd +.describeSupplied <- function(x) { + if (is.null(x)) { + return(cli::format_inline("{.code NULL}")) + } + if (is.atomic(x) && length(x) > 0) { + return(cli::format_inline("{.val {x}}")) + } + cli::format_inline("{.obj_type_friendly {x}}") +} diff --git a/man/checkClass.Rd b/man/checkClass.Rd index 38dc642c1..943921495 100644 --- a/man/checkClass.Rd +++ b/man/checkClass.Rd @@ -4,13 +4,15 @@ \alias{checkClass} \title{Checks that an object has the same class in all studies} \usage{ -checkClass(datasources = NULL, obj = NULL) +checkClass(datasources = NULL, obj = NULL, call = parent.frame()) } \arguments{ \item{datasources}{a list of \code{\link[DSI]{DSConnection-class}} objects obtained after login. If the the default set of connections will be used: see \link[DSI]{datashield.connections_default}.} \item{obj}{a string character, the name of the object to check for.} + +\item{call}{The frame to report the error from.} } \value{ a message or the class of the object if the object has the same class in all studies. diff --git a/man/glmChecks.Rd b/man/glmChecks.Rd index a645541ab..6db3ee480 100644 --- a/man/glmChecks.Rd +++ b/man/glmChecks.Rd @@ -4,7 +4,7 @@ \alias{glmChecks} \title{Checks if the elements in the glm model have the right characteristics} \usage{ -glmChecks(formula, data, offset, weights, datasources) +glmChecks(formula, data, offset, weights, datasources, call = parent.frame()) } \arguments{ \item{formula}{a character, a regression formula given as a string character} @@ -20,6 +20,8 @@ process. Should be NULL or a numeric vector.} \item{datasources}{a list of \code{\link[DSI]{DSConnection-class}} objects obtained after login. If the the default set of connections will be used: see \link[DSI]{datashield.connections_default}.} + +\item{call}{The frame to report the error from.} } \value{ an integer 0 if check was passed and 1 if failed diff --git a/man/isDefined.Rd b/man/isDefined.Rd index 6b2d0f7e9..231ce7fbf 100644 --- a/man/isDefined.Rd +++ b/man/isDefined.Rd @@ -4,7 +4,12 @@ \alias{isDefined} \title{Checks if the objects are defined in all studies} \usage{ -isDefined(datasources = NULL, obj = NULL, error.message = TRUE) +isDefined( + datasources = NULL, + obj = NULL, + error.message = TRUE, + call = parent.frame() +) } \arguments{ \item{datasources}{a list of \code{\link[DSI]{DSConnection-class}} objects obtained after login. @@ -16,6 +21,8 @@ used: see \code{\link[DSI]{datashield.connections_default}}.} \item{error.message}{a Boolean which specifies if the function should stop and return an error message when the input object is not defined in one or more studies or to return a list of TRUE/FALSE indicating in which studies the object is defined} + +\item{call}{The frame to report the error from.} } \value{ returns an error message if \code{error.message} argument is set to TRUE (default) diff --git a/tests/testthat/data_files/molgenis_armadillo-upload_testing_datasets.R b/tests/testthat/data_files/molgenis_armadillo-upload_testing_datasets.R index 9e1299710..759a85c0f 100644 --- a/tests/testthat/data_files/molgenis_armadillo-upload_testing_datasets.R +++ b/tests/testthat/data_files/molgenis_armadillo-upload_testing_datasets.R @@ -4,6 +4,9 @@ library(MolgenisArmadillo) +# arrow's multi-threaded write_parquet() intermittently corrupts memory and hangs the CI upload +options(arrow.use_threads = FALSE) # nolint: undesirable_function_linter. Must apply to the whole upload run + upload_testing_dataset_table <- function(project_name, folder_name, table_name, dataset_file_name) { dataset_name <- load(file = dataset_file_name) dataset <- eval(as.symbol(dataset_name)) diff --git a/tests/testthat/test-_-utils.R b/tests/testthat/test-_-utils.R new file mode 100644 index 000000000..f50643088 --- /dev/null +++ b/tests/testthat/test-_-utils.R @@ -0,0 +1,77 @@ +# +# Tests +# + +# context("utils::.checkArgProvided") +test_that(".checkArgProvided names the argument and reports the calling function", { + check <- function(x) .checkArgProvided(x, "the name of the input vector") + + expect_null(check("a")) + error <- expect_error(check(NULL), "`x` must be the name of the input vector") + expect_equal(error$call, quote(check(NULL))) +}) + +# context("utils::.abortInvalidChoice") +test_that(".abortInvalidChoice lists the allowed values and the value given", { + type <- "pooled" + expect_error(.abortInvalidChoice("type", c("combine", "split")), "`type` must be \"combine\" or \"split\", not \"pooled\"") + expect_error(.abortInvalidChoice("type", c("both", "combine", "split")), "`type` must be \"both\", \"combine\", or \"split\", not \"pooled\"") + type <- 0 + expect_error(.abortInvalidChoice("type", c("combine", "split")), "not 0") + type <- NULL + expect_error(.abortInvalidChoice("type", c("combine", "split")), "not `NULL`") +}) + +# context("utils::.resolveNewobjName") +test_that(".resolveNewobjName applies the default before validating", { + expect_equal(.resolveNewobjName(NULL, "x.newobj"), "x.newobj") + expect_equal(.resolveNewobjName("my.obj", "x.newobj"), "my.obj") +}) + +test_that(".resolveNewobjName rejects anything but a single character string", { + expect_error(.resolveNewobjName(23, "x.newobj"), "`newobj` must be a single character string") + expect_error(.resolveNewobjName(c("a", "b"), "x.newobj"), "`newobj` must be a single character string") + expect_error(.resolveNewobjName(23, "x.newobj"), "not 23") + expect_error(.checkNewobjName(NULL), "not `NULL`") +}) + +# context("utils::.verifyDatasources") +test_that(".verifyDatasources rejects objects that are not connections", { + expect_error(.verifyDatasources(list(1)), "`datasources` must be a list of objects") + expect_error(.verifyDatasources(list(1)), "Element 1 is 1\\.") +}) + +# context("utils::.checkClassConsistency") +test_that(".checkClassConsistency compares the chosen field across studies", { + same <- list(a = list(class = "numeric"), b = list(class = "numeric")) + different <- list(a = list(class = "numeric"), b = list(class = "factor")) + + expect_null(.checkClassConsistency(same)) + expect_error(.checkClassConsistency(different), "The input object must have the same class") + expect_error(.checkClassConsistency(different, objectName = "D"), "\"D\" must have the same class") + expect_error(.checkClassConsistency(different), "\"b\" has class ") +}) + +# context("utils::.seedAsText") +test_that(".seedAsText converts the seed and rejects anything that isn't a number", { + expect_equal(.seedAsText(NULL), "NULL") + expect_equal(.seedAsText(27), "27") + expect_error(.seedAsText("a"), "`seed.as.integer` must be an integer or `NULL`") + expect_error(.seedAsText("a"), "not \"a\"") +}) + +# context("utils::.checkArgsSet") +test_that(".checkArgsSet names every argument", { + expect_null(.checkArgsSet(a = 1, b = 2)) + expect_error(.checkArgsSet(a = NULL, b = 2), "`a` and `b` must all be set") + expect_error(.checkArgsSet(a = NULL, b = 2), "`a` is `NULL`") +}) + +# context("utils::.checkOffsetInFormula") +test_that(".checkOffsetInFormula rejects offset() and weights() terms in the formula", { + expect_null(.checkOffsetInFormula("y~x")) + expect_null(.checkOffsetInFormula("y~x+D$weights_kg+offset_var")) + expect_error(.checkOffsetInFormula("y~offset(x)"), "Found `offset\\(x\\)`") # nolint: nonportable_path_linter. Regex, not a file path + expect_error(.checkOffsetInFormula("y~x+weights(w)"), "can't contain `offset\\(\\)` or `weights\\(\\)`") # nolint: nonportable_path_linter. Regex, not a file path + expect_error(.checkOffsetInFormula(y ~ x + offset(z)), "Found `offset\\(z\\)`") # nolint: nonportable_path_linter. Regex, not a file path +}) diff --git a/tests/testthat/test-arg-ds.Boole.R b/tests/testthat/test-arg-ds.Boole.R index d8fb3bedf..ad828e875 100644 --- a/tests/testthat/test-arg-ds.Boole.R +++ b/tests/testthat/test-arg-ds.Boole.R @@ -21,11 +21,11 @@ connect.studies.dataset.cnsim(list("LAB_TSC", "LAB_TRIG")) # context("ds.Boole::arg::test errors") test_that("Boole_erros", { - expect_error(ds.Boole(), "Please provide the name of the column or scalar that holds V1!", fixed=TRUE) - expect_error(ds.Boole(V1="D$LAB_TSC"), "Please provide the name of a column or scalar holding V2 or declare a scalar in character format: eg '3'", fixed=TRUE) - expect_error(ds.Boole(V1="D$LAB_TSC", V2="LAB_TRIG"), "Please provide a Boolean operator in character format: eg '==' or '>=' or '<' or '!='", fixed=TRUE) - expect_error(ds.Boole(V1="D$LAB_TSC", V2="LAB_TRIG", Boolean.operator="==", na.assign=2), "Error: na.assign must be a character string taking value 'NA', '0' or '1'- if not specified default is 'NA'", fixed=TRUE) - expect_error(ds.Boole(V1="D$LAB_TSC", V2="LAB_TRIG", Boolean.operator="AA"), "An unrecognized Boolean operator, AA, has provide", fixed=TRUE) + expect_error(ds.Boole(), "must be the name of the column or scalar that holds V1", fixed=TRUE) + expect_error(ds.Boole(V1="D$LAB_TSC"), "must be the name of a column or scalar that holds V2", fixed=TRUE) + expect_error(ds.Boole(V1="D$LAB_TSC", V2="LAB_TRIG"), "must be a Boolean operator in character format", fixed=TRUE) + expect_error(ds.Boole(V1="D$LAB_TSC", V2="LAB_TRIG", Boolean.operator="==", na.assign=2), "must be \"NA\", \"0\", or \"1\"", fixed=TRUE) + expect_error(ds.Boole(V1="D$LAB_TSC", V2="LAB_TRIG", Boolean.operator="AA"), "`Boolean.operator` must be \"==\", \"!=\", \"<\", \"<=\", \">\", or \">=\", not\\s+\"AA\"") }) # diff --git a/tests/testthat/test-arg-ds.abs.R b/tests/testthat/test-arg-ds.abs.R index cfe0a49aa..c09eb9171 100644 --- a/tests/testthat/test-arg-ds.abs.R +++ b/tests/testthat/test-arg-ds.abs.R @@ -10,7 +10,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.abs::arg::test errors") test_that("abs_errors", { - expect_error(ds.abs(), "Please provide the name of the input object!", fixed=TRUE) + expect_error(ds.abs(), "must be the name of the input object", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.asCharacter.R b/tests/testthat/test-arg-ds.asCharacter.R index 8d7d35449..b3de6cbe9 100644 --- a/tests/testthat/test-arg-ds.asCharacter.R +++ b/tests/testthat/test-arg-ds.asCharacter.R @@ -21,7 +21,7 @@ connect.discordant.dataset.simple(list("A", "B", "C")) # context("ds.asCharacter::arg::test errors") test_that("asCharacter_erros", { - expect_error(ds.asCharacter(), "Please provide the name of the input vector!", fixed=TRUE) + expect_error(ds.asCharacter(), "must be the name of the input vector", fixed=TRUE) }) # context("ds.asCharacter::arg::discordant errors") diff --git a/tests/testthat/test-arg-ds.asDataMatrix.R b/tests/testthat/test-arg-ds.asDataMatrix.R index ca65f6cb0..c102de734 100644 --- a/tests/testthat/test-arg-ds.asDataMatrix.R +++ b/tests/testthat/test-arg-ds.asDataMatrix.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.asDataMatrix::arg::test errors") test_that("asDataMatrix_erros", { - expect_error(ds.asDataMatrix(), "Please provide the name of the input vector!", fixed=TRUE) + expect_error(ds.asDataMatrix(), "must be the name of the input vector", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.asFactor.R b/tests/testthat/test-arg-ds.asFactor.R index a264b040a..7e5467898 100644 --- a/tests/testthat/test-arg-ds.asFactor.R +++ b/tests/testthat/test-arg-ds.asFactor.R @@ -21,9 +21,9 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.asFactor::arg::test errors") test_that("asFactor_erros", { - expect_error(ds.asFactor(), "Please provide the name of the variable that is to be converted to a factor e.g. 'varname'", fixed=TRUE) - expect_error(ds.asFactor(input.var.name=1), "Please provide the name of the variable that is to be converted to a factor in character format e.g. 'varname'", fixed=TRUE) - expect_error(ds.asFactor(input.var.name=NA), "Please provide the name of the variable that is to be converted to a factor in character format e.g. 'varname'", fixed=TRUE) + expect_error(ds.asFactor(), "must be the name of the variable to convert", fixed=TRUE) + expect_error(ds.asFactor(input.var.name=1), "`input.var.name` must be a character string, such as \"varname\", not 1", fixed=TRUE) + expect_error(ds.asFactor(input.var.name=NA), "`input.var.name` must be a character string, such as \"varname\", not NA", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.asInteger.R b/tests/testthat/test-arg-ds.asInteger.R index c6305012e..fb11796ad 100644 --- a/tests/testthat/test-arg-ds.asInteger.R +++ b/tests/testthat/test-arg-ds.asInteger.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.asInteger::arg::test errors") test_that("asInteger_erros", { - expect_error(ds.asInteger(), "Please provide the name of the input vector!", fixed=TRUE) + expect_error(ds.asInteger(), "must be the name of the input vector", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.asList.R b/tests/testthat/test-arg-ds.asList.R index 926401881..4deb3e771 100644 --- a/tests/testthat/test-arg-ds.asList.R +++ b/tests/testthat/test-arg-ds.asList.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.asList::arg::test errors") test_that("asList_erros", { - expect_error(ds.asList(), "Please provide the name of the input vector!", fixed=TRUE) + expect_error(ds.asList(), "must be the name of the input vector", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.asLogical.R b/tests/testthat/test-arg-ds.asLogical.R index 39056cc38..18f06c355 100644 --- a/tests/testthat/test-arg-ds.asLogical.R +++ b/tests/testthat/test-arg-ds.asLogical.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.asLogical::arg::test errors") test_that("asLogical_erros", { - expect_error(ds.asLogical(), "Please provide the name of the input vector!", fixed=TRUE) + expect_error(ds.asLogical(), "must be the name of the input vector", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.asMatrix.R b/tests/testthat/test-arg-ds.asMatrix.R index 4a199dd08..af186d4fc 100644 --- a/tests/testthat/test-arg-ds.asMatrix.R +++ b/tests/testthat/test-arg-ds.asMatrix.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.asMatrix::arg::test errors") test_that("asMatrix_erros", { - expect_error(ds.asMatrix(), "Please provide the name of the input vector!", fixed=TRUE) + expect_error(ds.asMatrix(), "must be the name of the input vector", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.asNumeric.R b/tests/testthat/test-arg-ds.asNumeric.R index 276260751..d8fe241bc 100644 --- a/tests/testthat/test-arg-ds.asNumeric.R +++ b/tests/testthat/test-arg-ds.asNumeric.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.asNumeric::arg::test errors") test_that("asNumeric_erros", { - expect_error(ds.asNumeric(), "Please provide the name of the input vector!", fixed=TRUE) + expect_error(ds.asNumeric(), "must be the name of the input vector", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.assign.R b/tests/testthat/test-arg-ds.assign.R index 4fbd06c42..41bbbb307 100644 --- a/tests/testthat/test-arg-ds.assign.R +++ b/tests/testthat/test-arg-ds.assign.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.assign::arg::test errors") test_that("assign_erros", { - expect_error(ds.assign(), "Please give the name of object to assign or an expression to evaluate and assign.!\n") + expect_error(ds.assign(), "must be the name of the object to assign") }) # diff --git a/tests/testthat/test-arg-ds.auc.R b/tests/testthat/test-arg-ds.auc.R index 55978417a..a37b7526e 100644 --- a/tests/testthat/test-arg-ds.auc.R +++ b/tests/testthat/test-arg-ds.auc.R @@ -25,8 +25,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) test_that("ds.auc errors for null pred or y", { - expect_error(ds.auc(pred=NULL, y='y'), "Please provide the name of the vector with predicted values", fixed=TRUE) - expect_error(ds.auc(pred='pred', y=NULL), "Please provide the name of the outcome variable", fixed=TRUE) + expect_error(ds.auc(pred=NULL, y='y'), "must be the name of the vector of predicted values", fixed=TRUE) + expect_error(ds.auc(pred='pred', y=NULL), "must be the name of the outcome variable", fixed=TRUE) }) diff --git a/tests/testthat/test-arg-ds.c.R b/tests/testthat/test-arg-ds.c.R index 7a85cecb4..50b674b6f 100644 --- a/tests/testthat/test-arg-ds.c.R +++ b/tests/testthat/test-arg-ds.c.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.c::arg::test errors") test_that("simple c errors", { - expect_error(ds.c(), "x=NULL. Please provide the names of the objects to concatenate!") + expect_error(ds.c(), "must be the names of the objects to concatenate") }) # diff --git a/tests/testthat/test-arg-ds.cbind.R b/tests/testthat/test-arg-ds.cbind.R index a51988136..75c15051e 100644 --- a/tests/testthat/test-arg-ds.cbind.R +++ b/tests/testthat/test-arg-ds.cbind.R @@ -23,8 +23,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) test_that("cbind_erros", { ds.asList(x='D$LAB_TSC', newobj="as_list") - expect_error(ds.cbind(), "Please provide a vector of character strings holding the name of the input elements!", fixed=TRUE) - expect_error(ds.cbind(x="as_list", DataSHIELD.checks=TRUE), "Only objects of type 'data.frame', 'matrix', 'numeric', 'integer', 'character', 'factor' and 'logical' are allowed.", fixed=TRUE) + expect_error(ds.cbind(), "must be a vector of the names of the input elements", fixed=TRUE) + expect_error(ds.cbind(x="as_list", DataSHIELD.checks=TRUE), "\"as_list\" must be of class", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.changeRefGroup.R b/tests/testthat/test-arg-ds.changeRefGroup.R index e1a9977be..1f72dc8be 100644 --- a/tests/testthat/test-arg-ds.changeRefGroup.R +++ b/tests/testthat/test-arg-ds.changeRefGroup.R @@ -21,8 +21,8 @@ connect.studies.dataset.cnsim(list("DIS_AMI", "LAB_TSC")) # context("ds.changeRefGroup::arg::test errors") test_that("changeRefGroup_erros", { - expect_error(ds.changeRefGroup(), "Please provide the name of a vector of type factor!") - expect_error(ds.changeRefGroup(x="D$DIS_AMI"), " You must indicate a reference level - set the parameter 'ref'.") + expect_error(ds.changeRefGroup(), "must be the name of a factor") + expect_error(ds.changeRefGroup(x="D$DIS_AMI"), "must be a reference level") expect_error(ds.changeRefGroup(x="D$LAB_TSC", ref="LAB_TSC"), "There are some DataSHIELD errors, list them with datashield.errors()", fixed=TRUE) diff --git a/tests/testthat/test-arg-ds.class.R b/tests/testthat/test-arg-ds.class.R index c0bf5c7dd..dfe92485d 100644 --- a/tests/testthat/test-arg-ds.class.R +++ b/tests/testthat/test-arg-ds.class.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.class::arg::test errors") test_that("class_erros", { - expect_error(ds.class(), "Please provide the name of the input object!", fixed=TRUE) + expect_error(ds.class(), "must be the name of the input object", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.completeCases.R b/tests/testthat/test-arg-ds.completeCases.R index 8bb997338..81661f3f2 100644 --- a/tests/testthat/test-arg-ds.completeCases.R +++ b/tests/testthat/test-arg-ds.completeCases.R @@ -21,8 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.completeCases::arg::test errors") test_that("completeCases_errors", { - res <- ds.completeCases() - expect_equal(res, "Error: x1 must be a character string naming a serverside data.frame, matrix or vector", fixed = TRUE) + expect_error(ds.completeCases(), "must be a character string that names a server-side") }) # diff --git a/tests/testthat/test-arg-ds.cor.R b/tests/testthat/test-arg-ds.cor.R index 25acd2f3b..5d6156a4a 100644 --- a/tests/testthat/test-arg-ds.cor.R +++ b/tests/testthat/test-arg-ds.cor.R @@ -21,8 +21,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC", "LAB_TRIG")) # context("ds.cor::arg::test errors") test_that("cor_erros", { - expect_error(ds.cor(), 'x=NULL. Please provide the name of a matrix or dataframe or the names of two numeric vectors!', fixed=TRUE) - expect_error(ds.cor(x='D$LAB_TSC', y='D$LAB_TRIG', type='datashield'), 'Function argument "type" has to be either "combine" or "split"', fixed=TRUE) + expect_error(ds.cor(), "must be the name of a matrix, data.frame or numeric vector", fixed=TRUE) + expect_error(ds.cor(x='D$LAB_TSC', y='D$LAB_TRIG', type='datashield'), "must be \"combine\" or \"split\"", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.corTest.R b/tests/testthat/test-arg-ds.corTest.R index 76adc6f15..ba1711b20 100644 --- a/tests/testthat/test-arg-ds.corTest.R +++ b/tests/testthat/test-arg-ds.corTest.R @@ -22,8 +22,8 @@ connect.studies.dataset.survival(list("survtime", "time.id")) # context("ds.corTest::arg") test_that("simple arg test", { - expect_error(ds.corTest(), "x=NULL. Please provide the names of the 1st numeric vector!", fixed=TRUE) - expect_error(ds.corTest(x="D$survtime"), "y=NULL. Please provide the names of the 2nd numeric vector!", fixed=TRUE) + expect_error(ds.corTest(), "must be the name of the first numeric vector", fixed=TRUE) + expect_error(ds.corTest(x="D$survtime"), "must be the name of the second numeric vector", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.cov.R b/tests/testthat/test-arg-ds.cov.R index d713fe366..341d74116 100644 --- a/tests/testthat/test-arg-ds.cov.R +++ b/tests/testthat/test-arg-ds.cov.R @@ -21,8 +21,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC", "LAB_TRIG")) # context("ds.cov::arg::test errors") test_that("cov_erros", { - expect_error(ds.cov(), 'x=NULL. Please provide the name of a matrix or dataframe or the names of two numeric vectors!', fixed=TRUE) - expect_error(ds.cov(x='D$LAB_TSC', y='D$LAB_TRIG', type='datashield'), 'Function argument "type" has to be either "combine" or "split"', fixed=TRUE) + expect_error(ds.cov(), "must be the name of a matrix, data.frame or numeric vector", fixed=TRUE) + expect_error(ds.cov(x='D$LAB_TSC', y='D$LAB_TRIG', type='datashield'), "must be \"combine\" or \"split\"", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.dataFrame.R b/tests/testthat/test-arg-ds.dataFrame.R index 33fa65cf6..bec04a8a6 100644 --- a/tests/testthat/test-arg-ds.dataFrame.R +++ b/tests/testthat/test-arg-ds.dataFrame.R @@ -21,10 +21,10 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.dataFrame::arg::test errors") test_that("dataframe_erros", { - expect_error(ds.dataFrame(), "Please provide the name of the list that holds the input vectors!", fixed=TRUE) + expect_error(ds.dataFrame(), "must be the name of the list that holds the input vectors", fixed=TRUE) ds.asList(x='D$LAB_TSC', newobj="as_list") - expect_error(ds.dataFrame("as_list", DataSHIELD.checks=TRUE), "Only objects of type 'data.frame', 'matrix', 'numeric', 'integer', 'character', 'factor' and 'logical' are allowed.", fixed=TRUE) + expect_error(ds.dataFrame("as_list", DataSHIELD.checks=TRUE), "\"as_list\" must be of class", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.dataFrameSubset.R b/tests/testthat/test-arg-ds.dataFrameSubset.R index dfce52dce..af8626970 100644 --- a/tests/testthat/test-arg-ds.dataFrameSubset.R +++ b/tests/testthat/test-arg-ds.dataFrameSubset.R @@ -28,22 +28,22 @@ test_that("setup", { # context("ds.dataFrameSubset::arg::missing 'ds.name' arg errors") test_that("dataFrameSubset_erros", { - expect_error(ds.dataFrameSubset(), "Please provide the name of the data.frame to be subsetted as a character string: eg 'xxx'", fixed=TRUE) + expect_error(ds.dataFrameSubset(), "must be the name of the data.frame to subset", fixed=TRUE) }) # context("ds.dataFrameSubset::arg::missing 'V1' arg error") test_that("dataFrameSubset_erros", { - expect_error(ds.dataFrameSubset(df.name="D"), "Please provide the name of the column or scalar that holds V1 as a character string: eg 'xxx' or '3'", fixed=TRUE) + expect_error(ds.dataFrameSubset(df.name="D"), "`V1.name` must name a column or scalar as a character string, not\\s+`NULL`") # nolint: nonportable_path_linter. Regex, not a file path }) # context("ds.dataFrameSubset::arg::missing 'V2' arg error") test_that("dataFrameSubset_erros", { - expect_error(ds.dataFrameSubset(df.name="D", V1.name="LAB_TSC"), "Please provide the name of the column or scalar that holds V2 as a character string: eg 'xxx' or '3'", fixed=TRUE) + expect_error(ds.dataFrameSubset(df.name="D", V1.name="LAB_TSC"), "`V2.name` must name a column or scalar as a character string, not\\s+`NULL`") # nolint: nonportable_path_linter. Regex, not a file path }) # context("ds.dataFrameSubset::arg::missing 'Boolean.operator' arg error") test_that("dataFrameSubset_erros", { - expect_error(ds.dataFrameSubset(df.name="D", V1.name="LAB_TSC", V2.name="LAB_TSC"), "Unless you are only subsetting columns, please provide a Boolean operator in character format: eg '==' or '>=' or '<' or '!='. However, if either keep.cols or rm.cols is non-null because you want to subset columns and you specify both V1.name and V2.name as NULL (or 'ONES') and Boolean.operator as NULL,ds.dataFrameSubset will subset out the specified columns but will keep all rows.", fixed=TRUE) + expect_error(ds.dataFrameSubset(df.name="D", V1.name="LAB_TSC", V2.name="LAB_TSC"), "must be a Boolean operator in character format", fixed=TRUE) }) # context("ds.dataFrameSubset::arg::missing 'df.name' value server-side") diff --git a/tests/testthat/test-arg-ds.dim.R b/tests/testthat/test-arg-ds.dim.R index 2fa7d228c..4ebcfc3bd 100644 --- a/tests/testthat/test-arg-ds.dim.R +++ b/tests/testthat/test-arg-ds.dim.R @@ -21,8 +21,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.dim::arg::test errors") test_that("dim_erros", { - expect_error(ds.dim(), "Please provide the name of a data.frame or matrix!", fixed=TRUE) - expect_error(ds.dim(x="D", type = "other"), 'Function argument "type" has to be either "both", "combine" or "split"', fixed=TRUE) + expect_error(ds.dim(), "must be the name of a data.frame or matrix", fixed=TRUE) + expect_error(ds.dim(x="D", type = "other"), "must be \"both\", \"combine\", or \"split\"", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.exists.R b/tests/testthat/test-arg-ds.exists.R index 8ae2070d3..2ab9f06df 100644 --- a/tests/testthat/test-arg-ds.exists.R +++ b/tests/testthat/test-arg-ds.exists.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.exists::arg::test errors") test_that("simple exists errors", { - expect_error(ds.exists(), "Please provide the name of the input object!") + expect_error(ds.exists(), "must be the name of the input object") }) # diff --git a/tests/testthat/test-arg-ds.exp.R b/tests/testthat/test-arg-ds.exp.R index c851bba34..c947b1d72 100644 --- a/tests/testthat/test-arg-ds.exp.R +++ b/tests/testthat/test-arg-ds.exp.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.exp::arg::test errors") test_that("exp_erros", { - expect_error(ds.exp(), "Please provide the name of the input object!", fixed=TRUE) + expect_error(ds.exp(), "must be the name of the input object", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.gamlss.R b/tests/testthat/test-arg-ds.gamlss.R index c24f41efb..20e4908f7 100644 --- a/tests/testthat/test-arg-ds.gamlss.R +++ b/tests/testthat/test-arg-ds.gamlss.R @@ -21,9 +21,9 @@ connect.studies.dataset.gamlss(list("e3_bw", "e3_gac_None")) # context("ds.gamlss::arg::test errors") test_that("gamlss_errors", { - expect_error(ds.gamlss(), " Please provide a valid formula!", fixed=TRUE) - expect_error(ds.gamlss(formula="e3_bw ~ e3_gac_None", method="RG"), "Argument 'method' must be either 'RS', 'CG' or 'mixed'", fixed=TRUE) - expect_error(ds.gamlss(formula="e3_bw ~ e3_gac_None", method="RS", centiles=TRUE), "Provide the name of the explanatory variable in 'xvar' argument", fixed=TRUE) + expect_error(ds.gamlss(), "must be a valid formula", fixed=TRUE) + expect_error(ds.gamlss(formula="e3_bw ~ e3_gac_None", method="RG"), "must be \"RS\", \"CG\", or \"mixed\"", fixed=TRUE) + expect_error(ds.gamlss(formula="e3_bw ~ e3_gac_None", method="RS", centiles=TRUE), "`xvar` must name the explanatory variable when `centiles` is `TRUE`, not\\s+`NULL`") # nolint: nonportable_path_linter. Regex, not a file path }) # diff --git a/tests/testthat/test-arg-ds.glm.R b/tests/testthat/test-arg-ds.glm.R index fbf1a880f..f54c4721a 100644 --- a/tests/testthat/test-arg-ds.glm.R +++ b/tests/testthat/test-arg-ds.glm.R @@ -21,8 +21,13 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.glm::arg::test errors") test_that("glm_errors", { - expect_error(ds.glm(), " Please provide a valid regression formula!", fixed=TRUE) - expect_error(ds.glm("D$LAB_TSC~D$LAB_TSC"), " Please provide a valid 'family' argument!", fixed=TRUE) + expect_error(ds.glm(), "must be a valid regression formula", fixed=TRUE) + expect_error(ds.glm("D$LAB_TSC~D$LAB_TSC"), "must be a valid family", fixed=TRUE) +}) + +test_that("glm warns and returns NULL when the model doesn't converge", { + expect_warning(mod <- ds.glm("D$LAB_TSC~1", family = "gaussian", maxit = 1), "The model didn't converge after 1 iterations") + expect_null(mod) }) # diff --git a/tests/testthat/test-arg-ds.glmPredict.R b/tests/testthat/test-arg-ds.glmPredict.R index f0a2f2857..dab0976fc 100644 --- a/tests/testthat/test-arg-ds.glmPredict.R +++ b/tests/testthat/test-arg-ds.glmPredict.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC", "LAB_TRIG", "DIS_AMI", "DIS_DIAB", # context("ds.glmPredict::arg::test _glmname_ arg is correct object") test_that("glmPredict_errors", { - expect_error(ds.glmPredict(), " is not set, please specify it as a character string containing the name of a valid glm class object on the serverside", fixed=TRUE) + expect_error(ds.glmPredict(), "must be the name of a glm object on the server", fixed=TRUE) }) # context("ds.glmPredict::arg::setting up glm obj for further testing") @@ -47,7 +47,7 @@ test_that("glmPredict_errors", { # context("ds.glmPredict::arg::test _output.type_ arg is correct object") test_that("glmPredict_errors", { expect_error(ds.glmPredict("gaussian.glmslma.obj", newdataname = NULL, output.type = NULL), "missing value where TRUE/FALSE needed", fixed=TRUE) - expect_error(ds.glmPredict("gaussian.glmslma.obj", newdataname = NULL, output.type = 'blah'), " is not correctly set, please specify it as one of three character strings: 'link', 'response', or 'terms'", fixed=TRUE) + expect_error(ds.glmPredict("gaussian.glmslma.obj", newdataname = NULL, output.type = 'blah'), "must be \"link\", \"response\", or \"terms\"", fixed=TRUE) }) # context("ds.glmPredict::arg::test _se.fit_ arg is correct object") @@ -71,7 +71,7 @@ test_that("glmPredict_errors", { # context("ds.glmPredict::arg::test _na.action_ arg is correct object") test_that("glmPredict_errors", { - expect_error(ds.glmPredict("gaussian.glmslma.obj", newdataname = NULL, output.type = "response", se.fit = FALSE, dispersion = NULL, terms=NULL, na.action= "na.other"), " is not correctly set, please specify it as one of four character strings: 'na.fail', 'na.omit', 'na.exclude' or 'na.pass'", fixed = TRUE) + expect_error(ds.glmPredict("gaussian.glmslma.obj", newdataname = NULL, output.type = "response", se.fit = FALSE, dispersion = NULL, terms=NULL, na.action= "na.other"), "must be \"na.fail\"", fixed = TRUE) }) diff --git a/tests/testthat/test-arg-ds.glmSLMA.R b/tests/testthat/test-arg-ds.glmSLMA.R index f016e971b..ec1771032 100644 --- a/tests/testthat/test-arg-ds.glmSLMA.R +++ b/tests/testthat/test-arg-ds.glmSLMA.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.glmSLMA::arg::test errors") test_that("glmSLMA_errors", { - expect_error(ds.glmSLMA(), " Please provide a valid regression formula!", fixed=TRUE) + expect_error(ds.glmSLMA(), "must be a valid regression formula", fixed=TRUE) expect_error(ds.glmSLMA('D$LAB_TSC~D$LAB_TRIG', family="gaussian", newobj="gaussian.glmslma.obj"), "There are some DataSHIELD errors, list them with datashield.errors()", fixed=TRUE) res.errors<-datashield.errors() diff --git a/tests/testthat/test-arg-ds.glmerSLMA.R b/tests/testthat/test-arg-ds.glmerSLMA.R index 36c80bb5b..52421dcf1 100644 --- a/tests/testthat/test-arg-ds.glmerSLMA.R +++ b/tests/testthat/test-arg-ds.glmerSLMA.R @@ -27,7 +27,7 @@ test_that("setup", { # context("ds.glmerSLMA::arg::testing") test_that("simple glmerSLMA tesing (mis)use of arguments", { - expect_error(ds.glmerSLMA(formula = 'incid_rate ~ trtGrp + Male + (1|idDoctor)', dataName = 'D'), " Please provide a valid 'family' argument!", fixed=TRUE) + expect_error(ds.glmerSLMA(formula = 'incid_rate ~ trtGrp + Male + (1|idDoctor)', dataName = 'D'), "must be a valid family", fixed=TRUE) expect_error(ds.glmerSLMA(formula = 'diab_dis ~ trtGrp + Male + (1|idDoctor)', family='poisson', dataName = 'D'), "There are some DataSHIELD errors, list them with datashield.errors()", fixed=TRUE) @@ -37,8 +37,7 @@ test_that("simple glmerSLMA tesing (mis)use of arguments", { expect_length(errs$sim2, 0) expect_length(errs$sim3, 0) - res <- ds.glmerSLMA(formula = 'incid_rate ~ trtGrp + Male + (1|idDoctor)', family='poisson', dataName = 'D', control_type = 'xtol_rel') - expect_equal(res$errorMessage, "ERROR: if control_type is non-null, you must specify a valid control_value eg control_value<-1.0e-7",fixed=TRUE) + expect_error(ds.glmerSLMA(formula = 'incid_rate ~ trtGrp + Male + (1|idDoctor)', family='poisson', dataName = 'D', control_type = 'xtol_rel'), "must be set when") expect_error(ds.glmerSLMA(formula = 'incid_rate ~ trtGrp + Male + (1|idDoctor)', family='poisson', dataName = 'D', control_type = 'check.conv.grad',control_value = 'nothing'), "There are some DataSHIELD errors, list them with datashield.errors()", fixed=TRUE) errs <- datashield.errors() @@ -47,7 +46,7 @@ test_that("simple glmerSLMA tesing (mis)use of arguments", { expect_length(errs$sim2, 0) expect_length(errs$sim3, 0) - expect_error(ds.glmerSLMA(), " Please provide a valid regression formula!", fixed=TRUE) + expect_error(ds.glmerSLMA(), "must be a valid regression formula", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.isNA.R b/tests/testthat/test-arg-ds.isNA.R index 433857a75..50a2bc9d7 100644 --- a/tests/testthat/test-arg-ds.isNA.R +++ b/tests/testthat/test-arg-ds.isNA.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_HDL")) # context("ds.isNA::arg::errors") test_that("isNA errors", { - expect_error(ds.isNA(), "Please provide the name of the input vector!", fixed=TRUE) + expect_error(ds.isNA(), "must be the name of the input vector", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.isValid.R b/tests/testthat/test-arg-ds.isValid.R index 4d97f1fa9..65e81ee41 100644 --- a/tests/testthat/test-arg-ds.isValid.R +++ b/tests/testthat/test-arg-ds.isValid.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_HDL")) # context("ds.isValid::arg::errors") test_that("isValid errors", { - expect_error(ds.isValid(), "Please provide the name of the input vector!", fixed=TRUE) + expect_error(ds.isValid(), "must be the name of the input vector", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.kurtosis.R b/tests/testthat/test-arg-ds.kurtosis.R index 0d8118e12..48ddec0e9 100644 --- a/tests/testthat/test-arg-ds.kurtosis.R +++ b/tests/testthat/test-arg-ds.kurtosis.R @@ -27,10 +27,10 @@ test_that("setup", { # context("ds.kurtosis::arg::test errors") test_that("kurtosis_erros", { - expect_error(ds.kurtosis(), "Please provide the name of the input vector!", fixed=TRUE) - expect_error(ds.kurtosis(x='D$LAB_TSC', type='datashield'), "Function argument \"type\" has to be either \"both\", \"combine\" or \"split\"", fixed=TRUE) - expect_error(ds.kurtosis(x='D$LAB_TSC', method="0"), "method must be an integer between 1 and 3", fixed=TRUE) - expect_error(ds.kurtosis(x='D$LAB_TSC', method="4"), "method must be an integer between 1 and 3", fixed=TRUE) + expect_error(ds.kurtosis(), "must be the name of the input vector", fixed=TRUE) + expect_error(ds.kurtosis(x='D$LAB_TSC', type='datashield'), "must be \"both\", \"combine\", or \"split\"", fixed=TRUE) + expect_error(ds.kurtosis(x='D$LAB_TSC', method="0"), "must be 1, 2, or 3", fixed=TRUE) + expect_error(ds.kurtosis(x='D$LAB_TSC', method="4"), "must be 1, 2, or 3", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.length.R b/tests/testthat/test-arg-ds.length.R index 7e997842f..36785af17 100644 --- a/tests/testthat/test-arg-ds.length.R +++ b/tests/testthat/test-arg-ds.length.R @@ -21,8 +21,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.length::arg::test errors") test_that("length_erros", { - expect_error(ds.length(), "Please provide the name of the input object!", fixed=TRUE) - expect_error(ds.length(x='D$LAB_TSC', type='datashield'), 'Function argument "type" has to be either "both", "combine" or "split"', fixed=TRUE) + expect_error(ds.length(), "must be the name of the input object", fixed=TRUE) + expect_error(ds.length(x='D$LAB_TSC', type='datashield'), "must be \"both\", \"combine\", or \"split\"", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.levels.R b/tests/testthat/test-arg-ds.levels.R index ad2f5bde1..f35810f05 100644 --- a/tests/testthat/test-arg-ds.levels.R +++ b/tests/testthat/test-arg-ds.levels.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.levels::arg") test_that("simple levels", { - expect_error(ds.levels(), "Please provide the name of the input vector!", fixed=TRUE) + expect_error(ds.levels(), "must be the name of the input vector", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.lexis.R b/tests/testthat/test-arg-ds.lexis.R index 52d1657df..04133e4e0 100644 --- a/tests/testthat/test-arg-ds.lexis.R +++ b/tests/testthat/test-arg-ds.lexis.R @@ -21,17 +21,17 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.lexis::arg::test errors") test_that("lexis_erros", { - expect_error(ds.lexis(), "Please provide the name of the column that holds the subject IDs!", fixed=TRUE) + expect_error(ds.lexis(), "must be the name of the column that holds subject IDs", fixed=TRUE) }) # context("ds.lexis::arg::test intervalWidth") test_that("simple lexis", { - expect_error(ds.lexis(data='D', intervalWidth = NA, idCol = 'D$id', entryCol = 'D$starttime', exitCol = 'D$endtime', statusCol = 'D$cens', variables = c('D$age.60'), expandDF = 'EM.new'), "Please provide a (non-zero) single numeric value or vector to identify the survival time intervals", fixed = TRUE) - expect_error(ds.lexis(data='D', intervalWidth = NULL, idCol = 'D$id', entryCol = 'D$starttime', exitCol = 'D$endtime', statusCol = 'D$cens', variables = c('D$age.60'), expandDF = 'EM.new'), "Please provide a (non-zero) single numeric value or vector to identify the survival time intervals", fixed = TRUE) - expect_error(ds.lexis(data='D', intervalWidth = 0.0, idCol = 'D$id', entryCol = 'D$starttime', exitCol = 'D$endtime', statusCol = 'D$cens', variables = c('D$age.60'), expandDF = 'EM.new'), "Please provide a (non-zero) single numeric value or vector to identify the survival time intervals", fixed = TRUE) - expect_error(ds.lexis(data='D', intervalWidth = c(1.0, NA, 2.5), idCol = 'D$id', entryCol = 'D$starttime', exitCol = 'D$endtime', statusCol = 'D$cens', variables = c('D$age.60'), expandDF = 'EM.new'), "Please provide a (non-zero) single numeric value or vector to identify the survival time intervals", fixed = TRUE) + expect_error(ds.lexis(data='D', intervalWidth = NA, idCol = 'D$id', entryCol = 'D$starttime', exitCol = 'D$endtime', statusCol = 'D$cens', variables = c('D$age.60'), expandDF = 'EM.new'), "must be a non-zero numeric value or vector", fixed = TRUE) + expect_error(ds.lexis(data='D', intervalWidth = NULL, idCol = 'D$id', entryCol = 'D$starttime', exitCol = 'D$endtime', statusCol = 'D$cens', variables = c('D$age.60'), expandDF = 'EM.new'), "must be a non-zero numeric value or vector", fixed = TRUE) + expect_error(ds.lexis(data='D', intervalWidth = 0.0, idCol = 'D$id', entryCol = 'D$starttime', exitCol = 'D$endtime', statusCol = 'D$cens', variables = c('D$age.60'), expandDF = 'EM.new'), "must be a non-zero numeric value or vector", fixed = TRUE) + expect_error(ds.lexis(data='D', intervalWidth = c(1.0, NA, 2.5), idCol = 'D$id', entryCol = 'D$starttime', exitCol = 'D$endtime', statusCol = 'D$cens', variables = c('D$age.60'), expandDF = 'EM.new'), "must be a non-zero numeric value or vector", fixed = TRUE) expect_error(ds.lexis(data='D', intervalWidth = c(1.0, NULL.0, 2.5), idCol = 'D$id', entryCol = 'D$starttime', exitCol = 'D$endtime', statusCol = 'D$cens', variables = c('D$age.60'), expandDF = 'EM.new'), "object 'NULL.0' not found", fixed = TRUE) - expect_error(ds.lexis(data='D', intervalWidth = c(1.0, 0.0, 2.5), idCol = 'D$id', entryCol = 'D$starttime', exitCol = 'D$endtime', statusCol = 'D$cens', variables = c('D$age.60'), expandDF = 'EM.new'), "Please provide a (non-zero) single numeric value or vector to identify the survival time intervals", fixed = TRUE) + expect_error(ds.lexis(data='D', intervalWidth = c(1.0, 0.0, 2.5), idCol = 'D$id', entryCol = 'D$starttime', exitCol = 'D$endtime', statusCol = 'D$cens', variables = c('D$age.60'), expandDF = 'EM.new'), "must be a non-zero numeric value or vector", fixed = TRUE) # res <- ds.lexis(data='D', intervalWidth = c(1.0, 1.5, 2.5), idCol = 'D$id', entryCol = 'D$starttime', exitCol = 'D$endtime', statusCol = 'D$cens', variables = c('D$age.60'), expandDF = 'EM.new') diff --git a/tests/testthat/test-arg-ds.list.R b/tests/testthat/test-arg-ds.list.R index b2bc229d6..8ef1525b7 100644 --- a/tests/testthat/test-arg-ds.list.R +++ b/tests/testthat/test-arg-ds.list.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.list::arg::test errors") test_that("simple ds.list errors", { - expect_error(ds.list(), "x=NULL. Please provide the names of the objects to coerce into a list!") + expect_error(ds.list(), "must be the names of the objects to coerce into a list") }) # diff --git a/tests/testthat/test-arg-ds.lmerSLMA.R b/tests/testthat/test-arg-ds.lmerSLMA.R index 7f6b3aca3..7b83e1ced 100644 --- a/tests/testthat/test-arg-ds.lmerSLMA.R +++ b/tests/testthat/test-arg-ds.lmerSLMA.R @@ -38,13 +38,10 @@ test_that("simple lmerSLMA tesing (mis)use of arguments", { expect_length(errs$sim2, 0) expect_length(errs$sim3, 0) - res <- ds.lmerSLMA(formula = 'incid_rate ~ trtGrp + Male + (1|idDoctor)', dataName = 'D', control_type = 'xtol_rel') - expect_equal(res$errorMessage, "ERROR: if control_type is non-null, you must specify a valid control_value eg control_value<-1.0e-7", fixed=TRUE) -# res <- ds.lmerSLMA(formula = 'incid_rate ~ trtGrp + Male + (1|idDoctor)', dataName = 'D', control_type = 'xtol_rel',control_value = 'nothing') -# expect_equal(res$study1$errorMessage, "REAL() can only be applied to a 'numeric', not a 'logical'", fixed=TRUE) + expect_error(ds.lmerSLMA(formula = 'incid_rate ~ trtGrp + Male + (1|idDoctor)', dataName = 'D', control_type = 'xtol_rel'), "must be set when") - expect_error(ds.lmerSLMA(), " Please provide a valid regression formula!", fixed=TRUE) + expect_error(ds.lmerSLMA(), "must be a valid regression formula", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.log.R b/tests/testthat/test-arg-ds.log.R index b51cdf7d4..167fc0757 100644 --- a/tests/testthat/test-arg-ds.log.R +++ b/tests/testthat/test-arg-ds.log.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.log::arg::test errors") test_that("log_erros", { - expect_error(ds.log(), "Please provide the name of the input vector!", fixed=TRUE) + expect_error(ds.log(), "must be the name of the input vector", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.ls.R b/tests/testthat/test-arg-ds.ls.R index bf24b112d..f305751d5 100644 --- a/tests/testthat/test-arg-ds.ls.R +++ b/tests/testthat/test-arg-ds.ls.R @@ -27,20 +27,11 @@ test_that("setup", { # context("ds.ls::arg") test_that("containing escape sequence", { - res1 <- ds.ls(search.filter="_:A:_Environment") + expect_error(ds.ls(search.filter="_:A:_Environment"), "also appears") - expect_length(res1, 1) - expect_equal(res1, "Warning: Code replacing wildcard (i.e. '*') is '_:A:_' but this appears in your original search filter string - please respecify") + expect_error(ds.ls(search.filter="Envir_:A:_oment"), "also appears") - res2 <- ds.ls(search.filter="Envir_:A:_oment") - - expect_length(res2, 1) - expect_equal(res2, "Warning: Code replacing wildcard (i.e. '*') is '_:A:_' but this appears in your original search filter string - please respecify") - - res3 <- ds.ls(search.filter="Environment_:A:_") - - expect_length(res3, 1) - expect_equal(res3, "Warning: Code replacing wildcard (i.e. '*') is '_:A:_' but this appears in your original search filter string - please respecify") + expect_error(ds.ls(search.filter="Environment_:A:_"), "also appears") }) # diff --git a/tests/testthat/test-arg-ds.make.R b/tests/testthat/test-arg-ds.make.R index 170b6f113..c23ee9f8f 100644 --- a/tests/testthat/test-arg-ds.make.R +++ b/tests/testthat/test-arg-ds.make.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.make::arg::test errors") test_that("make_erros", { - expect_error(ds.make(), "Please give the name of object to assign or an expression to evaluate and assign.!\n", fixed=TRUE) + expect_error(ds.make(), "must be the name of the object to assign", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.matrix.R b/tests/testthat/test-arg-ds.matrix.R index c6cf9089e..ece363542 100644 --- a/tests/testthat/test-arg-ds.matrix.R +++ b/tests/testthat/test-arg-ds.matrix.R @@ -21,9 +21,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.matrix::arg::test errors") test_that("matrix_erros", { - res <- ds.matrix(mdata=NULL) + expect_error(ds.matrix(mdata=NULL), "must be a character string, numeric vector or scalar") - expect_equal(res, "Error: mdata must be a character string, a numeric vector or a scalar") }) # diff --git a/tests/testthat/test-arg-ds.matrixDet.R b/tests/testthat/test-arg-ds.matrixDet.R index c598d81b7..265a8005f 100644 --- a/tests/testthat/test-arg-ds.matrixDet.R +++ b/tests/testthat/test-arg-ds.matrixDet.R @@ -21,9 +21,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.matrixDet::arg::test errors") test_that("matrixDet_erros", { - res <- ds.matrixDet() + expect_error(ds.matrixDet(), "must be the name of the matrix that represents M1") - expect_equal(res, "Error: Please provide the name of the matrix representing M1") }) # diff --git a/tests/testthat/test-arg-ds.matrixDet.report.R b/tests/testthat/test-arg-ds.matrixDet.report.R index d76b92392..10d028ced 100644 --- a/tests/testthat/test-arg-ds.matrixDet.report.R +++ b/tests/testthat/test-arg-ds.matrixDet.report.R @@ -22,9 +22,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.matrixDet.report::arg::test errors") test_that("ds.matixDet.report erros", { - res <- ds.matrixDet.report(M1=NULL) + expect_error(ds.matrixDet.report(M1=NULL), "must be the name of the matrix that represents M1") - expect_equal(res, "Error: Please provide the name of the matrix representing M1") }) # diff --git a/tests/testthat/test-arg-ds.matrixDiag.R b/tests/testthat/test-arg-ds.matrixDiag.R index 0dc152ff2..9003e658a 100644 --- a/tests/testthat/test-arg-ds.matrixDiag.R +++ b/tests/testthat/test-arg-ds.matrixDiag.R @@ -21,10 +21,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.matrixDiag::arg::test errors") test_that("matrixDiag_erros", { - res <- ds.matrixDiag() + expect_error(ds.matrixDiag(), "must be a character string, numeric vector or scalar") - expect_length(res, 1) - expect_equal(res, "Error: x1 must have a value which is a character string, a numeric vector or a scalar", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.matrixDimnames.R b/tests/testthat/test-arg-ds.matrixDimnames.R index c6da09344..5f149cdbe 100644 --- a/tests/testthat/test-arg-ds.matrixDimnames.R +++ b/tests/testthat/test-arg-ds.matrixDimnames.R @@ -21,9 +21,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.matrixDimnames::arg::test errors") test_that("matrixDimnames_erros", { - res <- ds.matrixDimnames() + expect_error(ds.matrixDimnames(), "must be the name of the matrix that represents M1") - expect_equal(res, "Error: Please provide the name of the matrix representing M1") }) # diff --git a/tests/testthat/test-arg-ds.matrixInvert.R b/tests/testthat/test-arg-ds.matrixInvert.R index dfed18dd6..afc50a1d5 100644 --- a/tests/testthat/test-arg-ds.matrixInvert.R +++ b/tests/testthat/test-arg-ds.matrixInvert.R @@ -21,9 +21,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.matrixInvert::arg::test errors") test_that("matrixInvert_erros", { - res <- ds.matrixInvert() + expect_error(ds.matrixInvert(), "must be the name of the matrix that represents M1") - expect_equal(res, "Error: Please provide the name of the matrix representing M1") }) # diff --git a/tests/testthat/test-arg-ds.matrixMult.R b/tests/testthat/test-arg-ds.matrixMult.R index 95564e0d5..9e5274d3d 100644 --- a/tests/testthat/test-arg-ds.matrixMult.R +++ b/tests/testthat/test-arg-ds.matrixMult.R @@ -21,9 +21,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.matrixMult::arg::test errors") test_that("matrixMult_erros", { - res <- ds.matrixMult() + expect_error(ds.matrixMult(), "must be the name of the matrix that represents M1") - expect_equal(res, "Error: Please provide the name of the matrix representing M1") }) # diff --git a/tests/testthat/test-arg-ds.matrixTranspose.R b/tests/testthat/test-arg-ds.matrixTranspose.R index d78c69041..d9d2e7853 100644 --- a/tests/testthat/test-arg-ds.matrixTranspose.R +++ b/tests/testthat/test-arg-ds.matrixTranspose.R @@ -21,9 +21,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.matrixTranspose::arg::test errors") test_that("matrixTranspose_erros", { - res <- ds.matrixTranspose() + expect_error(ds.matrixTranspose(), "must be the name of the matrix that represents M1") - expect_equal(res, "Error: Please provide the name of the matrix representing M1") }) # diff --git a/tests/testthat/test-arg-ds.mean.R b/tests/testthat/test-arg-ds.mean.R index 36c365bc5..f99961119 100644 --- a/tests/testthat/test-arg-ds.mean.R +++ b/tests/testthat/test-arg-ds.mean.R @@ -21,8 +21,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.mean::arg::test errors") test_that("mean_erros", { - expect_error(ds.mean(), "Please provide the name of the input object!", fixed=TRUE) - expect_error(ds.mean(x='D$LAB_TSC', type='datashield'), 'Function argument "type" has to be either "both", "combine" or "split"', fixed=TRUE) + expect_error(ds.mean(), "must be the name of the input object", fixed=TRUE) + expect_error(ds.mean(x='D$LAB_TSC', type='datashield'), "must be \"both\", \"combine\", or \"split\"", fixed=TRUE) }) #context("ds.mean::arg::discordant errors") diff --git a/tests/testthat/test-arg-ds.meanSdGp.R b/tests/testthat/test-arg-ds.meanSdGp.R index bac7b2c46..23db6fde3 100644 --- a/tests/testthat/test-arg-ds.meanSdGp.R +++ b/tests/testthat/test-arg-ds.meanSdGp.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.meanSdGp::arg::test errors") test_that("meanSdGp_erros", { - expect_error(ds.meanSdGp(), "Please provide the name of the input vector!", fixed=TRUE) + expect_error(ds.meanSdGp(), "must be the name of the input vector", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.merge.R b/tests/testthat/test-arg-ds.merge.R index 03a6967a7..19d3a54c4 100644 --- a/tests/testthat/test-arg-ds.merge.R +++ b/tests/testthat/test-arg-ds.merge.R @@ -21,11 +21,11 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.merge::arg::test errors") test_that("merge_erros", { - expect_error(ds.merge(), "Please provide the name (eg 'name1') of first dataframe to be merged (called x) ", fixed=TRUE) - expect_error(ds.merge(x.name="A"), "Please provide the name (eg 'name2') of second dataframe to be merged (called y) ", fixed=TRUE) + expect_error(ds.merge(), "must be the name of the first data.frame to merge", fixed=TRUE) + expect_error(ds.merge(x.name="A"), "must be the name of the second data.frame to merge", fixed=TRUE) expect_error(ds.merge(x.name="D$LAB_TSC", y.name="B", by.x.names="LAB_TSC", by.y.names="LAB_TSC"), "DataSHIELD errors") - expect_error(ds.merge(x.name="D$LAB_TSC", y.name="D$LAB_TSC", by.x.names="C"), "Please provide the names of columns in y dataframe on which to merge (eg c('id', 'time'))", fixed=TRUE) - expect_error(ds.merge(x.name="D$LAB_TSC", y.name="D$LAB_TSC", by.x.names="D$LAB_TSC", by.y.names="D", suffixes=NULL), "Please provide the suffixes to append to disambiguate duplicate column names (default = c('.x','.y'))", fixed=TRUE) + expect_error(ds.merge(x.name="D$LAB_TSC", y.name="D$LAB_TSC", by.x.names="C"), "must be the names of the columns in y to merge on", fixed=TRUE) + expect_error(ds.merge(x.name="D$LAB_TSC", y.name="D$LAB_TSC", by.x.names="D$LAB_TSC", by.y.names="D", suffixes=NULL), "must be the suffixes that separate duplicate column names", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.mice.R b/tests/testthat/test-arg-ds.mice.R index a90c9c166..84bf9d7a8 100644 --- a/tests/testthat/test-arg-ds.mice.R +++ b/tests/testthat/test-arg-ds.mice.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.mice::arg::test errors") test_that("mice_errors", { - expect_error(ds.mice(), "Please provide the name of the dataframe or matrix that contains the incomplete data!", fixed=TRUE) + expect_error(ds.mice(), "must be the name of the data.frame or matrix", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.names.R b/tests/testthat/test-arg-ds.names.R index 3faa397a7..62d72c4ce 100644 --- a/tests/testthat/test-arg-ds.names.R +++ b/tests/testthat/test-arg-ds.names.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.names::arg::test errors") test_that("simple ds.names errors", { - expect_error(ds.names(), "Please provide the name of the input list!", fixed=TRUE) + expect_error(ds.names(), "must be the name of the input list", fixed=TRUE) res.errors <- DSI::datashield.errors() diff --git a/tests/testthat/test-arg-ds.ns.R b/tests/testthat/test-arg-ds.ns.R index 56fb58f5a..ff83bf883 100644 --- a/tests/testthat/test-arg-ds.ns.R +++ b/tests/testthat/test-arg-ds.ns.R @@ -28,7 +28,7 @@ test_that("setup", { # context("ds.ns::arg::test errors") test_that("ns_errors", { expect_error(ds.ns(), "argument \"x\" is missing, with no default", fixed=TRUE) - expect_error(ds.qlspline(x=NULL), "Please provide the name of the input variable x!", fixed=TRUE) + expect_error(ds.qlspline(x=NULL), "must be the name of the input variable", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.numNA.R b/tests/testthat/test-arg-ds.numNA.R index be436303a..bdfd02940 100644 --- a/tests/testthat/test-arg-ds.numNA.R +++ b/tests/testthat/test-arg-ds.numNA.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.numNA::arg::test errors") test_that("simple ds.numNA errors", { - expect_error(ds.numNA(), "Please provide the name of a vector!") + expect_error(ds.numNA(), "must be the name of a vector") }) # diff --git a/tests/testthat/test-arg-ds.qlspline.R b/tests/testthat/test-arg-ds.qlspline.R index c7ff7650a..3dacd636c 100644 --- a/tests/testthat/test-arg-ds.qlspline.R +++ b/tests/testthat/test-arg-ds.qlspline.R @@ -28,9 +28,9 @@ test_that("setup", { # context("ds.qlspline::arg::test errors") test_that("qlspline_errors", { expect_error(ds.qlspline(), "argument \"x\" is missing, with no default", fixed=TRUE) - expect_error(ds.qlspline(x=NULL), "Please provide the name of the input variable x!", fixed=TRUE) + expect_error(ds.qlspline(x=NULL), "must be the name of the input variable", fixed=TRUE) expect_error(ds.qlspline(x='D$PM_BMI_CONTINUOUS'), "argument \"q\" is missing, with no default", fixed=TRUE) - expect_error(ds.qlspline(x='D$PM_BMI_CONTINUOUS', q=NULL), "Argument 'q' is missing, with no default!", fixed=TRUE) + expect_error(ds.qlspline(x='D$PM_BMI_CONTINUOUS', q=NULL), "must be a number of quantiles", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.quantileMean.R b/tests/testthat/test-arg-ds.quantileMean.R index ef7784341..e762218a7 100644 --- a/tests/testthat/test-arg-ds.quantileMean.R +++ b/tests/testthat/test-arg-ds.quantileMean.R @@ -21,8 +21,8 @@ connect.studies.dataset.cnsim(list('LAB_HDL')) # context("ds.quantileMean::arg::test errors") test_that("quantileMean_erros", { - expect_error(ds.quantileMean(), "Please provide the name of the input vector!", fixed=TRUE) - expect_error(ds.quantileMean(x='D$LAB_HDL', type='datashield'), 'Function argument "type" has to be either "combine" or "split"', fixed=TRUE) + expect_error(ds.quantileMean(), "must be the name of the input vector", fixed=TRUE) + expect_error(ds.quantileMean(x='D$LAB_HDL', type='datashield'), "must be \"combine\" or \"split\"", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.rBinom.R b/tests/testthat/test-arg-ds.rBinom.R index 8d4100bde..bb5119f05 100644 --- a/tests/testthat/test-arg-ds.rBinom.R +++ b/tests/testthat/test-arg-ds.rBinom.R @@ -21,10 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.rBinom::arg::test errors") test_that("rBinom_erros", { - error.message <- ds.rBinom(seed.as.integer='Value') - - expect_equal(class(error.message), 'character') - expect_equal(error.message, 'ERROR failed: seed.as.integer must be set as an integer [numeric] or left NULL') + expect_error(ds.rBinom(seed.as.integer='Value'), "must be an integer or") }) # diff --git a/tests/testthat/test-arg-ds.rNorm.R b/tests/testthat/test-arg-ds.rNorm.R index d4ec8075b..215dfd3b2 100644 --- a/tests/testthat/test-arg-ds.rNorm.R +++ b/tests/testthat/test-arg-ds.rNorm.R @@ -21,10 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.rNorm::arg::test errors") test_that("rNorm_erros", { - error.message <- ds.rNorm(seed.as.integer='Value') - - expect_equal(class(error.message), 'character') - expect_equal(error.message, 'ERROR failed: seed.as.integer must be set as an integer [numeric] or left NULL') + expect_error(ds.rNorm(seed.as.integer='Value'), "must be an integer or") }) # diff --git a/tests/testthat/test-arg-ds.rPois.R b/tests/testthat/test-arg-ds.rPois.R index 707ca3813..18177209e 100644 --- a/tests/testthat/test-arg-ds.rPois.R +++ b/tests/testthat/test-arg-ds.rPois.R @@ -21,10 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.rPois::arg::test errors") test_that("rPois_erros", { - error.message <- ds.rPois(seed.as.integer='Value') - - expect_equal(class(error.message), 'character') - expect_equal(error.message, 'ERROR failed: seed.as.integer must be set as an integer [numeric] or left NULL') + expect_error(ds.rPois(seed.as.integer='Value'), "must be an integer or") }) # diff --git a/tests/testthat/test-arg-ds.rUnif.R b/tests/testthat/test-arg-ds.rUnif.R index be046e8e5..48f3024a8 100644 --- a/tests/testthat/test-arg-ds.rUnif.R +++ b/tests/testthat/test-arg-ds.rUnif.R @@ -21,10 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.rUnif::arg::test errors") test_that("rUnif_erros", { - error.message <- ds.rUnif(seed.as.integer='Value') - - expect_equal(class(error.message), 'character') - expect_equal(error.message, 'ERROR failed: seed.as.integer must be set as an integer [numeric] or left NULL') + expect_error(ds.rUnif(seed.as.integer='Value'), "must be an integer or") }) # diff --git a/tests/testthat/test-arg-ds.rbind.R b/tests/testthat/test-arg-ds.rbind.R index 3a4ed9f27..c7da6de8a 100644 --- a/tests/testthat/test-arg-ds.rbind.R +++ b/tests/testthat/test-arg-ds.rbind.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.rbind::arg::test errors") test_that("rbind_erros", { - expect_error(ds.rbind(), "Please provide a vector of character strings holding the name of the input elements!", fixed=TRUE) + expect_error(ds.rbind(), "must be a vector of the names of the input elements", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.reShape.R b/tests/testthat/test-arg-ds.reShape.R index ed8e8102b..4a7084227 100644 --- a/tests/testthat/test-arg-ds.reShape.R +++ b/tests/testthat/test-arg-ds.reShape.R @@ -21,10 +21,10 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.reShape::arg::test errors") test_that("reShape_erros", { - expect_error(ds.reShape(), "Please provide the name of the list that holds the input vectors!", fixed=TRUE) - expect_error(ds.reShape(data.name="test", sep=TRUE), "'sep' must be a character string", fixed=TRUE) - expect_error(ds.reShape(data.name="test", sep=""), "'sep' must be a character string", fixed=TRUE) - expect_error(ds.reShape(data.name="test", sep="ts"), "'sep' must be a character string", fixed=TRUE) + expect_error(ds.reShape(), "must be the name of the list that holds the input vectors", fixed=TRUE) + expect_error(ds.reShape(data.name="test", sep=TRUE), "must be a single character", fixed=TRUE) + expect_error(ds.reShape(data.name="test", sep=""), "must be a single character", fixed=TRUE) + expect_error(ds.reShape(data.name="test", sep="ts"), "must be a single character", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.recodeValues.R b/tests/testthat/test-arg-ds.recodeValues.R index 74a2da507..ab2d89e16 100644 --- a/tests/testthat/test-arg-ds.recodeValues.R +++ b/tests/testthat/test-arg-ds.recodeValues.R @@ -21,13 +21,13 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.recodeValues::arg::test errors") test_that("recodeValues_erros", { - expect_error(ds.recodeValues(), "Please provide the name of the variable to be recoded: eg 'xxx'", fixed=TRUE) - expect_error(ds.recodeValues('D$LAB_TSC'), "Please provide a vector in the 'values2replace.vector' argument specifying\n the values to be replaced eg c(1,7)", fixed=TRUE) - expect_error(ds.recodeValues('D$LAB_TSC', values2replace.vector=c(0,1)), "Please ensure that values2replace.vector and new.values.vector have same length and are in the same order", fixed=TRUE) - expect_error(ds.recodeValues('D$LAB_TSC', values2replace.vector=c(0,1), new.values.vector=c(-10)), "Please ensure that values2replace.vector and new.values.vector have same length and are in the same order", fixed=TRUE) - expect_error(ds.recodeValues('D$LAB_TSC', values2replace.vector=c(1,1), new.values.vector=c(-10, 10)), "No value may appear more than once in the values2replace.vector", fixed=TRUE) - expect_error(ds.recodeValues('D$LAB_TSC', values2replace.vector=c(NA), new.values.vector=c(10)), "To recode NAs you need to use the 'missing' argument", fixed=TRUE) - expect_error(ds.recodeValues('D$LAB_TSC', missing=99), "Please provide a vector in the 'values2replace.vector' argument specifying\n the values to be replaced eg c(1,7)", fixed=TRUE) + expect_error(ds.recodeValues(), "must be the name of the variable to recode", fixed=TRUE) + expect_error(ds.recodeValues('D$LAB_TSC'), "must specify the values to replace", fixed=TRUE) + expect_error(ds.recodeValues('D$LAB_TSC', values2replace.vector=c(0,1)), "`new.values.vector` must specify the new values, not `NULL`", fixed=TRUE) + expect_error(ds.recodeValues('D$LAB_TSC', values2replace.vector=c(0,1), new.values.vector=c(-10)), "`values2replace.vector` and `new.values.vector` must have the same", fixed=TRUE) + expect_error(ds.recodeValues('D$LAB_TSC', values2replace.vector=c(1,1), new.values.vector=c(-10, 10)), "must not contain duplicate values", fixed=TRUE) + expect_error(ds.recodeValues('D$LAB_TSC', values2replace.vector=c(NA), new.values.vector=c(10)), "`values2replace.vector` can't contain `NA`", fixed=TRUE) + expect_error(ds.recodeValues('D$LAB_TSC', missing=99), "must specify the values to replace", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.rep.R b/tests/testthat/test-arg-ds.rep.R index f9c2ec6ba..0791c2be3 100644 --- a/tests/testthat/test-arg-ds.rep.R +++ b/tests/testthat/test-arg-ds.rep.R @@ -24,9 +24,8 @@ connect.studies.dataset.survival(list("survtime", "time.id", "female")) # context("ds.rep::arg::test errors") test_that("ds.rep erros", { - res <- ds.rep() + expect_error(ds.rep(), "must be a character string, a client-side numeric vector") - expect_equal(res, "Error: x1 must have a value which is a character string, a numeric vector on the clientside or a scalar", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.replaceNA.R b/tests/testthat/test-arg-ds.replaceNA.R index acd8c7b7e..6cff90c4f 100644 --- a/tests/testthat/test-arg-ds.replaceNA.R +++ b/tests/testthat/test-arg-ds.replaceNA.R @@ -21,8 +21,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.replaceNA::arg::test errors") test_that("simple ds.replaceNA errors", { - expect_error(ds.replaceNA(), "Please provide the name of a vector!", fixed=TRUE) - expect_error(ds.replaceNA(x="D$LAB_TSC"), "Please provide a list of replacement values!", fixed=TRUE) + expect_error(ds.replaceNA(), "must be the name of a vector", fixed=TRUE) + expect_error(ds.replaceNA(x="D$LAB_TSC"), "must be a list of replacement values", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.rm.R b/tests/testthat/test-arg-ds.rm.R index bb674bca1..22d50b8d5 100644 --- a/tests/testthat/test-arg-ds.rm.R +++ b/tests/testthat/test-arg-ds.rm.R @@ -22,7 +22,7 @@ connect.studies.dataset.survival(list("survtime", "time.id", "female")) # context("ds.rm::arg::test errors") test_that("ds.rm erros", { - expect_error(ds.rm(), "Please provide the names of the objects to be deleted (eg 'object.name') as the x.names argument", fixed=TRUE) + expect_error(ds.rm(), "must be the names of the objects to delete", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.rowColCalc.R b/tests/testthat/test-arg-ds.rowColCalc.R index 76b8604bb..8077d1a27 100644 --- a/tests/testthat/test-arg-ds.rowColCalc.R +++ b/tests/testthat/test-arg-ds.rowColCalc.R @@ -21,9 +21,9 @@ connect.studies.dataset.cnsim(list("LAB_TSC", "LAB_HDL")) # context("ds.rowColCalc::arg::test errors") test_that("rowColCalc_errors", { - expect_error(ds.rowColCalc(), "Please provide the name of a data.frame or matrix!", fixed=TRUE) - expect_error(ds.rowColCalc(x='D', newobj="rsum_hdl_tsc"), "'operation' = NULL. Please set it to 'rowSums', 'colSums', 'rowMeans' or 'colMeans'", fixed=TRUE) - expect_error(ds.rowColCalc(x='D', newobj="rsum_hdl_tsc", operation="datashield"), "'operation' must be set to: 'rowSums', 'colSums', 'rowMeans' or 'colMeans'", fixed=TRUE) + expect_error(ds.rowColCalc(), "must be the name of a data.frame or matrix", fixed=TRUE) + expect_error(ds.rowColCalc(x='D', newobj="rsum_hdl_tsc"), "`operation` must be \"rowSums\", \"colSums\", \"rowMeans\", or \"colMeans\", not\\s+`NULL`") + expect_error(ds.rowColCalc(x='D', newobj="rsum_hdl_tsc", operation="datashield"), "must be \"rowSums\", \"colSums\", \"rowMeans\", or \"colMeans\"", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.sample.R b/tests/testthat/test-arg-ds.sample.R index f84f4c3e7..6b19a43bc 100644 --- a/tests/testthat/test-arg-ds.sample.R +++ b/tests/testthat/test-arg-ds.sample.R @@ -23,12 +23,9 @@ connect.studies.dataset.cnsim(list("LAB_TSC", "LAB_TRIG")) # context("ds.sample::arg::test errors") test_that("cov_erros", { - res1 <- ds.sample() - expect_equal(res1, 'Error: x must denote a character string naming the serverside object to be sampled or an integer N denoting permute 1:N', fixed=TRUE) - res2 <- ds.sample(x='D$LAB_TSC') - expect_equal(res2, 'Error: size must have a value which is an integer denoting how many records to be sampled', fixed=TRUE) - res3 <- ds.sample(x='D$LAB_TSC', size=1234, seed.as.integer="FooBar") - expect_equal(res3, 'ERROR failed: seed.as.integer must be set as an integer [numeric] or left NULL', fixed=TRUE) + expect_error(ds.sample(), "must be a character string that names a server-side object") + expect_error(ds.sample(x='D$LAB_TSC'), "must be an integer that sets how many records") + expect_error(ds.sample(x='D$LAB_TSC', size=1234, seed.as.integer="FooBar"), "must be an integer or") }) # diff --git a/tests/testthat/test-arg-ds.setSeed.R b/tests/testthat/test-arg-ds.setSeed.R index 1bf41b5ca..4d5010409 100644 --- a/tests/testthat/test-arg-ds.setSeed.R +++ b/tests/testthat/test-arg-ds.setSeed.R @@ -21,9 +21,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.setSeed::arg::test errors") test_that("setSeed_erros", { - res <- ds.setSeed(seed.as.integer="Test") + expect_error(ds.setSeed(seed.as.integer="Test"), "must be an integer or") - expect_equal(res, "ERROR terminated: seed.as.integer must be set as an integer [numeric] or as being NULL") }) # diff --git a/tests/testthat/test-arg-ds.skewness.R b/tests/testthat/test-arg-ds.skewness.R index 6a9440cc7..848589510 100644 --- a/tests/testthat/test-arg-ds.skewness.R +++ b/tests/testthat/test-arg-ds.skewness.R @@ -27,10 +27,10 @@ test_that("setup", { # context("ds.skewness::arg::test errors") test_that("skewness_erros", { - expect_error(ds.skewness(), "Please provide the name of the input vector!", fixed=TRUE) - expect_error(ds.skewness(x='D$LAB_TSC', type='datashield'), "Function argument \"type\" has to be either \"both\", \"combine\" or \"split\"", fixed=TRUE) - expect_error(ds.skewness(x='D$LAB_TSC', method="0"), "method must be an integer between 1 and 3", fixed=TRUE) - expect_error(ds.skewness(x='D$LAB_TSC', method="4"), "method must be an integer between 1 and 3", fixed=TRUE) + expect_error(ds.skewness(), "must be the name of the input vector", fixed=TRUE) + expect_error(ds.skewness(x='D$LAB_TSC', type='datashield'), "must be \"both\", \"combine\", or \"split\"", fixed=TRUE) + expect_error(ds.skewness(x='D$LAB_TSC', method="0"), "must be 1, 2, or 3", fixed=TRUE) + expect_error(ds.skewness(x='D$LAB_TSC', method="4"), "must be 1, 2, or 3", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.sqrt.R b/tests/testthat/test-arg-ds.sqrt.R index ce4248649..5905864c2 100644 --- a/tests/testthat/test-arg-ds.sqrt.R +++ b/tests/testthat/test-arg-ds.sqrt.R @@ -10,7 +10,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.sqrt::arg::test errors") test_that("sqrt_errors", { - expect_error(ds.sqrt(), "Please provide the name of the input object!", fixed=TRUE) + expect_error(ds.sqrt(), "must be the name of the input object", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.summary.R b/tests/testthat/test-arg-ds.summary.R index e3d386568..78158c33c 100644 --- a/tests/testthat/test-arg-ds.summary.R +++ b/tests/testthat/test-arg-ds.summary.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.summary::arg::test errors") test_that("summary_erros", { - expect_error(ds.summary(), "Please provide the name of the input vector!", fixed=TRUE) + expect_error(ds.summary(), "must be the name of the input vector", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.table.R b/tests/testthat/test-arg-ds.table.R index ae781fe20..eaf9b3267 100644 --- a/tests/testthat/test-arg-ds.table.R +++ b/tests/testthat/test-arg-ds.table.R @@ -21,33 +21,30 @@ connect.studies.dataset.cnsim(list("DIS_CVA", "DIS_AMI", "LAB_TSC", "LAB_HDL")) # context("ds.table::arg::test rvar has value") test_that("table rvar has value", { - res <- ds.table() + expect_error(ds.table(), "must be a character string that names the row variable") - expect_equal(res, "Error: rvar must have a value which is a character string naming the row variable for the table", fixed=TRUE) }) # context("ds.table::arg::test cvar has value") test_that("table cvar has value", { - res <- ds.table(rvar="D$LAB_TSC", cvar=30) + expect_error(ds.table(rvar="D$LAB_TSC", cvar=30), "must be a character string that names the column variable") - expect_equal(res, "Error: if cvar is not null, it must have a value which is a character string naming the column variable for the table", fixed=TRUE) }) # context("ds.table::arg::test stvar has value") test_that("table stvar has value", { - res <- ds.table(rvar="D$LAB_TSC", cvar=NULL, stvar=25) + expect_error(ds.table(rvar="D$LAB_TSC", cvar=NULL, stvar=25), "must be a character string that names the variable") - expect_equal(res, "Error: if stvar is not null, it must have a value which is a character string naming the variable coding separate tables for the table", fixed=TRUE) }) # context("ds.table::arg::test stvar has CORRECT value") test_that("table useNA has value", { - expect_error(ds.table(rvar="D$LAB_TSC", cvar=NULL, stvar=NULL, useNA = c("BEN")), "useNA must be either 'no' or 'always'.", fixed = TRUE) + expect_error(ds.table(rvar="D$LAB_TSC", cvar=NULL, stvar=NULL, useNA = c("BEN")), "must be \"no\" or \"always\"", fixed = TRUE) }) # context("ds.table::arg::test force.nfilter has value") test_that("table force.nfilter has value", { - expect_error(ds.table(rvar="D$LAB_TSC", cvar=NULL, stvar=NULL, useNA = c("ifany"), force.nfilter =30), "useNA must be either 'no' or 'always'.", fixed = TRUE) + expect_error(ds.table(rvar="D$LAB_TSC", cvar=NULL, stvar=NULL, useNA = c("ifany"), force.nfilter =30), "must be \"no\" or \"always\"", fixed = TRUE) }) diff --git a/tests/testthat/test-arg-ds.tapply.R b/tests/testthat/test-arg-ds.tapply.R index 5ac42edf5..2bbca9ad2 100644 --- a/tests/testthat/test-arg-ds.tapply.R +++ b/tests/testthat/test-arg-ds.tapply.R @@ -21,22 +21,14 @@ connect.studies.dataset.cnsim(list("LAB_TSC", "GENDER")) # context("ds.tapply::arg::test errors") test_that("tapply_erros", { - res1 <- ds.tapply() + expect_error(ds.tapply(), "must be the name of the variable to summarise") - expect_length(res1, 1) - expect_equal(res1, "Error: Please provide the name of the variable to be summarized, as a character string") - res2 <- ds.tapply('D$LAB_TSC') + expect_error(ds.tapply('D$LAB_TSC'), "must name a single factor or a list of factors") - expect_length(res2, 3) - expect_equal(res2$Error.message, "Error: Please provide the name of the single factor or") - expect_equal(res2$Err.cont2, "the list of factors to index the variable to be summarized.") - expect_equal(res2$Err.cont3, "In either case the argument must be specified in inverted commas") - res3 <- ds.tapply('D$LAB_TSC', 'D$GENDER') + expect_error(ds.tapply('D$LAB_TSC', 'D$GENDER'), "must be a valid summarising function") - expect_length(res3, 1) - expect_equal(res3, "Error: Please provide a valid summarizing function, as a character string") }) # diff --git a/tests/testthat/test-arg-ds.tapply.assign.R b/tests/testthat/test-arg-ds.tapply.assign.R index 14ea83890..b14bad48e 100644 --- a/tests/testthat/test-arg-ds.tapply.assign.R +++ b/tests/testthat/test-arg-ds.tapply.assign.R @@ -21,22 +21,14 @@ connect.studies.dataset.cnsim(list("LAB_TSC", "GENDER")) # context("ds.tapply.assign::arg::test errors") test_that("tapply_erros", { - res1 <- ds.tapply.assign() + expect_error(ds.tapply.assign(), "must be the name of the variable to summarise") - expect_length(res1, 1) - expect_equal(res1, "Error: Please provide the name of the variable to be summarized, as a character string") - res2 <- ds.tapply.assign('D$LAB_TSC') + expect_error(ds.tapply.assign('D$LAB_TSC'), "must name a single factor or a list of factors") - expect_length(res2, 3) - expect_equal(res2$Error.message, "Error: Please provide the name of the single factor or") - expect_equal(res2$Err.cont2, "the list of factors to index the variable to be summarized.") - expect_equal(res2$Err.cont3, "In either case the argument must be specified in inverted commas") - res3 <- ds.tapply.assign('D$LAB_TSC', 'D$GENDER') + expect_error(ds.tapply.assign('D$LAB_TSC', 'D$GENDER'), "must be a valid summarising function") - expect_length(res3, 1) - expect_equal(res3, "Error: Please provide a valid summarizing function, as a character string") }) # diff --git a/tests/testthat/test-arg-ds.unList.R b/tests/testthat/test-arg-ds.unList.R index 2d3aa4877..9016b05cd 100644 --- a/tests/testthat/test-arg-ds.unList.R +++ b/tests/testthat/test-arg-ds.unList.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.unList::arg::test errors") test_that("unList_erros", { - expect_error(ds.unList(), "Please provide the name of the input vector!", fixed=TRUE) + expect_error(ds.unList(), "must be the name of the input vector", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-ds.unique.R b/tests/testthat/test-arg-ds.unique.R index a0e112a59..ba207f717 100644 --- a/tests/testthat/test-arg-ds.unique.R +++ b/tests/testthat/test-arg-ds.unique.R @@ -21,12 +21,12 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.unique::arg::no arguments") test_that("simple ds.unique no arguments", { - expect_error(ds.unique(), "x.name=NULL. Please provide the names of the objects to de-duplicated!", fixed = TRUE) + expect_error(ds.unique(), "must be the names of the objects to de-duplicate", fixed = TRUE) }) # context("ds.unique::arg::NULL arguments") test_that("simple ds.unique NULL arguments", { - expect_error(ds.unique(NULL), "x.name=NULL. Please provide the names of the objects to de-duplicated!", fixed = TRUE) + expect_error(ds.unique(NULL), "must be the names of the objects to de-duplicate", fixed = TRUE) }) # diff --git a/tests/testthat/test-arg-ds.var.R b/tests/testthat/test-arg-ds.var.R index e745cbcfc..27ab699a1 100644 --- a/tests/testthat/test-arg-ds.var.R +++ b/tests/testthat/test-arg-ds.var.R @@ -21,7 +21,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.var::arg::test errors") test_that("var_erros", { - expect_error(ds.var(), "Please provide the name of the input object!", fixed=TRUE) + expect_error(ds.var(), "must be the name of the input object", fixed=TRUE) }) # diff --git a/tests/testthat/test-arg-error-messages.R b/tests/testthat/test-arg-error-messages.R new file mode 100644 index 000000000..ac164a249 --- /dev/null +++ b/tests/testthat/test-arg-error-messages.R @@ -0,0 +1,271 @@ + +# +# Set up +# + +# context("error messages::arg::setup") + +studies <- list(sim1 = "study1", sim2 = "study2", sim3 = "study3") + +# Replaces the server with canned replies, named by server function. A reply that is a +# function is called with the study name and the expression, so it can differ between them. +fake_server <- function(..., env = parent.frame()) { + replies <- list(...) + answer <- function(conns, expr, ...) { + reply <- replies[[sub("\\(.*$", "", as.character(expr)[[1]])]] + study_names <- stats::setNames(names(conns), names(conns)) + lapply(study_names, function(study) if (is.function(reply)) reply(study, expr) else reply) + } + assign_nothing <- function(...) invisible(NULL) + local_mocked_bindings(datashield.aggregate = answer, datashield.assign = assign_nothing, # nolint: object_usage_linter. testthat is a Suggests dep, not installed when lint runs + .package = "DSI", .env = env) + local_mocked_bindings(datashield.aggregate = answer, datashield.assign = assign_nothing, # nolint: object_usage_linter. testthat is a Suggests dep, not installed when lint runs + .resolveDatasources = function(datasources) datasources, .env = env) +} + +missing_pattern <- function(columns, count = "5") { + pattern <- matrix(1, nrow = 2, ncol = length(columns), dimnames = list(c(count, ""), columns)) + list(pattern = pattern, valid = TRUE, message = "Valid") +} + +one_bar <- structure(list(breaks = 1:2, counts = 1, density = 1, mids = 1.5, xname = "x", equidist = TRUE), # nolint: undesirable_function_linter. + class = "histogram") + +# +# Tests +# + +# context("error messages::arg::argument checks") +test_that("ds.asFactorSimple rejects a name that is not a character string", { + fake_server() + expect_error(ds.asFactorSimple(input.var.name = 1, datasources = studies), "`input.var.name` must be a character string") +}) + +test_that("ds.dmtC2S rejects missing and unsupported data", { + fake_server() + expect_error(ds.dmtC2S(dfdata = NULL, datasources = studies), "`dfdata` must be a character string") + expect_error(ds.dmtC2S(dfdata = 1, datasources = studies), "`dfdata` must be a , , or , not 1") +}) + +test_that("ds.elspline rejects fewer than two knots", { + fake_server() + expect_error(ds.elspline(x = "a", n = 1, datasources = studies), "`n` must be greater than or equal to 2") +}) + +test_that("ds.forestplot rejects a variable that is not in the model", { + betas <- matrix(1, dimnames = list("age", "study1")) + mod <- list(num.valid.studies = 1, output.summary = list(study1 = 1, input.beta.matrix.for.SLMA = betas, input.se.matrix.for.SLMA = betas)) + expect_error(ds.forestplot(mod, variable = "bmi"), "not \"bmi\"") +}) + +test_that("ds.getWGSR rejects a missing thirdPart and an invalid standing", { + fake_server() + expect_error(ds.getWGSR(sex = "s", firstPart = "a", secondPart = "b", index = "bfa", datasources = studies), "`thirdPart` must be provided") + expect_error(ds.getWGSR(sex = "s", firstPart = "a", secondPart = "b", index = "hfa", standing = 4, datasources = studies), "`standing` must be 1, 2, or 3, not 4") +}) + +test_that("ds.glmSummary rejects a name that is not a character string", { + fake_server() + expect_error(ds.glmSummary(x.name = 1, datasources = studies), "`x.name` must be a character string") +}) + +test_that("ds.metadata rejects a missing or invalid name", { + fake_server() + expect_error(ds.metadata(x = NULL, datasources = studies), "`x` must be the name of an object") + expect_error(ds.metadata(x = 1, datasources = studies), "`x` must be a single character string") +}) + +test_that("ds.rBinom rejects missing and out-of-range arguments", { + fake_server() + expect_error(ds.rBinom(samp.size = NULL, newobj = "x", datasources = studies), "must all be set") + expect_error(ds.rBinom(size = -1, prob = 0.5, newobj = "x", datasources = studies), "`size` must be greater than 0") + expect_error(ds.rBinom(size = 1, prob = 2, newobj = "x", datasources = studies), "`prob` must be between 0 and 1") +}) + +test_that("ds.rNorm rejects missing and out-of-range arguments", { + fake_server() + expect_error(ds.rNorm(samp.size = NULL, datasources = studies), "must all be set") + expect_error(ds.rNorm(sd = -1, datasources = studies), "`sd` must be greater than 0") + expect_error(ds.rNorm(force.output.to.k.decimal.places = 10, datasources = studies), "must be an integer between 0 and 9") +}) + +test_that("ds.rPois rejects missing and out-of-range arguments", { + fake_server() + expect_error(ds.rPois(samp.size = NULL, datasources = studies), "must all be set") + expect_error(ds.rPois(lambda = 0, datasources = studies), "`lambda` must be greater than 0") +}) + +test_that("ds.rUnif rejects missing and out-of-range arguments", { + fake_server() + expect_error(ds.rUnif(samp.size = NULL, datasources = studies), "must all be set") + expect_error(ds.rUnif(min = 2, max = 1, datasources = studies), "`max` must be greater than `min`") + expect_error(ds.rUnif(force.output.to.k.decimal.places = 10, datasources = studies), "must be an integer between 0 and 9") +}) + +test_that("ds.replaceNA rejects the wrong number of replacement values", { + fake_server(numNaDS = list(numNA = 2)) + expect_error(ds.replaceNA("x", forNA = list(1), datasources = studies), "`forNA` must have one element per study") + expect_error(ds.replaceNA("x", forNA = list(1:3, 1:3, 1:3), datasources = studies), "Replacement values must have length 1") +}) + +test_that("ds.rowColCalc rejects a missing operation", { + fake_server() + expect_error(ds.rowColCalc("x", operation = NULL, datasources = studies), "`operation` must be \"rowSums\"") +}) + +test_that("ds.seq rejects each invalid argument", { + fake_server() + expect_error(ds.seq(FROM.value.char = 1, TO.value.char = "2", datasources = studies), "`FROM.value.char` must be a real number") + expect_error(ds.seq(TO.value.char = 2, datasources = studies), "`TO.value.char` must be a real number") + expect_error(ds.seq(BY.value.char = 1, TO.value.char = "2", datasources = studies), "`BY.value.char` must be a real number") + expect_error(ds.seq(LENGTH.OUT.value.char = 1, datasources = studies), "`LENGTH.OUT.value.char` must be an integer") + expect_error(ds.seq(ALONG.WITH.name = 1, datasources = studies), "`ALONG.WITH.name` must be the name") + expect_error(ds.seq(datasources = studies), "must be set") +}) + +test_that("ds.tapply and ds.tapply.assign reject more than two factors", { + fake_server() + expect_error(ds.tapply("x", c("a", "b", "c"), "sum", datasources = studies), "`INDEX.names` must name no more than two factors") + expect_error(ds.tapply.assign("x", c("a", "b", "c"), "sum", datasources = studies), "`INDEX.names` must name no more than two factors") +}) + +test_that("ds.table rejects a force.nfilter that is not a character string", { + fake_server() + expect_error(ds.table("r", force.nfilter = 3, datasources = studies), "`force.nfilter` must be a character string") +}) + +# context("error messages::arg::warnings before the server call") +test_that("ds.changeRefGroup warns about reorderByRef", { + fake_server() + expect_warning(ds.changeRefGroup("x", ref = "a", reorderByRef = TRUE, datasources = studies), "`reorderByRef` is `TRUE`") +}) + +test_that("model functions reject an offset or weights in the formula", { + fake_server() + formula <- "y~x+offset(z)" + pattern <- "Found `offset\\(z\\)`" # nolint: nonportable_path_linter. Regex, not a file path + expect_error(ds.glm(formula, datasources = studies), pattern) + expect_error(ds.glmSLMA(formula, datasources = studies), pattern) + expect_error(ds.glmerSLMA(formula, datasources = studies), pattern) + expect_error(ds.lmerSLMA(formula, datasources = studies), pattern) +}) + +# context("error messages::arg::server replies") +test_that("checkClass rejects classes that differ across studies", { + fake_server(classDS = function(study, expr) if (study == "sim1") "numeric" else "character") + expect_error(checkClass(studies, "x"), "\"x\" must have the same class in all studies") +}) + +test_that("isDefined names the studies that lack the object", { + fake_server(exists = function(study, expr) study != "sim2") + expect_error(isDefined(studies, "x"), "\"x\" isn't defined in \"sim2\"") +}) + +test_that("ds.asFactor reports levels the server failed to find", { + fake_server(asFactorDS1 = "FAILED: too many levels") + expect_error(ds.asFactor("x", datasources = studies), "Can't obtain the factor levels") +}) + +test_that("ds.boxPlot rejects a class it can't plot", { + fake_server(classDS = "character") + expect_error(ds.boxPlot("x", datasources = studies), "`x` must be a or vector") +}) + +test_that("ds.rbind and ds.summary reject an unsupported class", { + fake_server(classDS = "function") + expect_error(ds.rbind("x", DataSHIELD.checks = TRUE, datasources = studies), "\"x\" must be of class") + expect_error(ds.summary("x", datasources = studies), "`x` must be of class") +}) + +test_that("ds.cbind and ds.dataFrame warn about duplicate names and reject unequal rows", { + fake_server(classDS = "numeric") + local_mocked_bindings(ds.length = function(x, ...) list(if (x == "a") 3 else 4)) # nolint: object_usage_linter. testthat is a Suggests dep, not installed when lint runs + x <- c("b", "a", "a") + expect_warning( + expect_error(ds.cbind(x, DataSHIELD.checks = TRUE, datasources = studies[1]), "All components must have the same number of rows"), + "column names in \"sim1\" are duplicated" + ) + expect_warning( + expect_error(ds.dataFrame(x, DataSHIELD.checks = TRUE, datasources = studies[1]), "All components must have the same number of rows"), + "column names in \"sim1\" are duplicated" + ) +}) + +test_that("ds.histogram reports missing break points and invalid cells", { + fake_server( + histogramDS1 = list(range = c(1, 2)), + histogramDS2 = function(study, expr) if (study == "sim1") list(histobject = one_bar, invalidcells = 2) + ) + expect_error(ds.histogram("x", datasources = studies), "Can't find equidistant break points") + expect_warning(ds.histogram("x", datasources = studies[1]), "In \"sim1\", 2 bins had fewer than") + + fake_server(histogramDS1 = list(range = c(1, 2)), histogramDS2 = list(histobject = one_bar, invalidcells = 2)) + warnings <- capture_warnings(ds.histogram("x", datasources = studies[1:2])) + expect_match(warnings, "In \"sim1\", 2 bins had fewer than", all = FALSE) + expect_match(warnings, "In \"sim2\", 2 bins had fewer than", all = FALSE) +}) + +test_that("ds.kurtosis and ds.skewness report too few observations for a combined result", { + fake_server() + local_mocked_bindings(ds.mean = function(...) list(Global.Mean = matrix(NA, 1, 1, dimnames = list(NULL, "EstimatedMean")))) # nolint: object_usage_linter. testthat is a Suggests dep, not installed when lint runs + expect_error(ds.kurtosis("x", type = "combine", datasources = studies), "number of valid observations in at least one study") + expect_error(ds.skewness("x", type = "combine", datasources = studies), "number of valid observations in at least one study") +}) + +test_that("ds.mdPattern warns about suppressed patterns and rejects patterns it can't pool", { + suppressed <- function(study, expr) { + result <- missing_pattern(c("a", "")) + result$valid <- study != "sim2" + result + } + fake_server(mdPatternDS = suppressed) + expect_warning(ds.mdPattern("x", type = "combine", datasources = studies), "suppressed by disclosure control") + + fake_server(mdPatternDS = function(study, expr) missing_pattern(if (study == "sim1") c("a", "") else c("a", "b", ""))) + expect_error(ds.mdPattern("x", type = "combine", datasources = studies), "different numbers of variables") + + fake_server(mdPatternDS = function(study, expr) missing_pattern(if (study == "sim1") c("a", "") else c("b", ""))) + expect_error(ds.mdPattern("x", type = "combine", datasources = studies), "studies have different variables") +}) + +test_that("ds.table reports factors it can't obtain and tables that differ in shape", { + levels_except <- function(name) function(study, expr) if (expr[[2]] != name) "1" + fake_server(asFactorDS1 = levels_except("r")) + expect_error(ds.table("r", datasources = studies), "Can't obtain factors for `rvar`") + fake_server(asFactorDS1 = levels_except("c")) + expect_error(ds.table("r", "c", datasources = studies), "Can't obtain factors for `cvar`") + fake_server(asFactorDS1 = levels_except("s")) + expect_error(ds.table("r", "c", "s", datasources = studies), "Can't obtain factors for `stvar`") + + fake_server(asFactorDS1 = "1", tableDS = function(study, expr) if (study == "sim1") table(1) else table(1, 1)) + expect_error(suppressMessages(ds.table("r", datasources = studies)), "different numbers of dimensions") +}) + +test_that("glmChecks reports variables that fail its checks", { + formula <- D$y ~ D$x + fake_server(exists = FALSE) + expect_error(suppressMessages(glmChecks(y ~ 1, NULL, NULL, NULL, studies[1])), "\"y\" isn't defined in \"sim1\"") + + fake_server(exists = TRUE, isNaDS = list(is.na = TRUE)) + expect_error(suppressMessages(glmChecks(formula, NULL, NULL, NULL, studies[1])), "\"D\\$y\" has only missing values in \"sim1\"") + + fake_server(exists = TRUE, isNaDS = list(is.na = FALSE), classDS = "character") + expect_error(suppressMessages(glmChecks(formula, NULL, "D$o", NULL, studies[1])), "\"D\\$o\" must be in \"sim1\"") + + fake_server(exists = TRUE, isNaDS = list(is.na = FALSE), classDS = "numeric", checkNegValueDS = TRUE) + expect_error(suppressMessages(glmChecks(formula, NULL, NULL, "D$w", studies[1])), "Weights \"D\\$w\" must not be negative in \"sim1\"") +}) + +test_that("ds.meanSdGp rejects invalid tables", { + fake_server(meanSdGpDS = list(Table_valid = FALSE)) + expect_error(ds.meanSdGp("x", "y", classConsistencyCheck = FALSE, datasources = studies), "At least one cell count is below") +}) + +test_that("ds.glm and ds.glmSLMA stop when a study's data is invalid", { + invalid <- list(list(NA, 1), "x", 1, 0, 0, 0, 0, errorMessage = "No errors") + fake_server(glmDS1 = invalid) + suppressMessages(expect_error(ds.glm("y~x", family = "gaussian", datasources = studies), "because of a data error")) + + fake_server(glmDS2 = list(disclosure.risk = 1, 1, 1, 1, 1, 1, 1, 1, 1, "No errors"), glmDS1 = list(list(NA, 1), "x", 0, 0, 0, 0, 0, errorMessage = "No errors")) + suppressMessages(expect_error(ds.glm("y~x", family = "gaussian", datasources = studies), "potential disclosure risk")) +}) diff --git a/tests/testthat/test-arg-per-study-arguments.R b/tests/testthat/test-arg-per-study-arguments.R index c8ee48d30..d12cff631 100644 --- a/tests/testthat/test-arg-per-study-arguments.R +++ b/tests/testthat/test-arg-per-study-arguments.R @@ -11,13 +11,13 @@ studies <- list(sim1 = "study1", sim2 = "study2", sim3 = "study3") record_server_calls <- function(env = parent.frame()) { sent <- new.env() sent$calls <- list() - testthat::local_mocked_bindings( + local_mocked_bindings( # nolint: object_usage_linter. testthat is a Suggests dep, not installed when lint runs datashield.assign = function(conns, symbol, value, ...) { sent$calls[[length(sent$calls) + 1]] <- value invisible(NULL) }, datashield.aggregate = function(conns, expr, ...) list(), - .set_datasources = function(datasources) datasources, + .resolveDatasources = function(datasources) datasources, .env = env ) sent @@ -27,18 +27,18 @@ record_server_calls <- function(env = parent.frame()) { # Tests # -# context("per-study arguments::arg::.expand_to_studies") -test_that(".expand_to_studies repeats a single value for every study", { - expect_equal(.expand_to_studies(5, "x", 3), c(5, 5, 5)) +# context("per-study arguments::arg::.expandToStudies") +test_that(".expandToStudies repeats a single value for every study", { + expect_equal(.expandToStudies(5, "x", 3), c(5, 5, 5)) }) -test_that(".expand_to_studies keeps one value per study", { - expect_equal(.expand_to_studies(c(1, 2, 3), "x", 3), c(1, 2, 3)) +test_that(".expandToStudies keeps one value per study", { + expect_equal(.expandToStudies(c(1, 2, 3), "x", 3), c(1, 2, 3)) }) -test_that(".expand_to_studies rejects any other length", { - expect_error(.expand_to_studies(c(1, 2), "x", 3), "'x' must be length 1 or one value per\\s+study") - expect_error(.expand_to_studies(c(1, 2, 3, 4), "x", 3), "'x' must be length 1 or one value per\\s+study") +test_that(".expandToStudies rejects any other length", { + expect_error(.expandToStudies(c(1, 2), "x", 3), "must have length 1 or 3 \\(one value per study\\), not 1 and 2") # nolint: nonportable_path_linter. Regex, not a file path + expect_error(.expandToStudies(c(1, 2, 3, 4), "x", 3), "must have length 1") }) # context("per-study arguments::arg::ds.rBinom") @@ -65,16 +65,15 @@ test_that("ds.rBinom sends a single size and prob to every study", { test_that("ds.rBinom rejects size or prob with the wrong number of values", { sent <- record_server_calls() - expect_error(ds.rBinom(samp.size = 10, size = c(1, 10), prob = 0.5, newobj = "x", seed.as.integer = 27, datasources = studies), "'size' must be length 1 or one value per\\s+study") - expect_error(ds.rBinom(samp.size = 10, size = 5, prob = c(0.1, 0.5), newobj = "x", seed.as.integer = 27, datasources = studies), "'prob' must be length 1 or one value per\\s+study") + expect_error(ds.rBinom(samp.size = 10, size = c(1, 10), prob = 0.5, newobj = "x", seed.as.integer = 27, datasources = studies), "must have length 1") + expect_error(ds.rBinom(samp.size = 10, size = 5, prob = c(0.1, 0.5), newobj = "x", seed.as.integer = 27, datasources = studies), "must have length 1") expect_length(sent$calls, 0) }) test_that("ds.rBinom checks every study's prob", { sent <- record_server_calls() - res <- ds.rBinom(samp.size = 10, size = 5, prob = c(0.5, 1.5, 0.5), newobj = "x", seed.as.integer = 27, datasources = studies) + expect_error(ds.rBinom(samp.size = 10, size = 5, prob = c(0.5, 1.5, 0.5), newobj = "x", seed.as.integer = 27, datasources = studies), "must be between 0 and 1") - expect_equal(res, "ERROR: prob must lie in range 0 < prob < 1") expect_length(sent$calls, 0) }) @@ -112,17 +111,16 @@ test_that("ds.rNorm sends a single mean, sd and decimal places to every study", test_that("ds.rNorm rejects mean, sd or decimal places with the wrong number of values", { sent <- record_server_calls() - expect_error(ds.rNorm(samp.size = 10, mean = c(0, 100), sd = 1, newobj = "x", seed.as.integer = 27, datasources = studies), "'mean' must be length 1 or one value per\\s+study") - expect_error(ds.rNorm(samp.size = 10, mean = 0, sd = c(1, 2), newobj = "x", seed.as.integer = 27, datasources = studies), "'sd' must be length 1 or one value per\\s+study") - expect_error(ds.rNorm(samp.size = 10, mean = 0, sd = 1, force.output.to.k.decimal.places = c(2, 4), newobj = "x", seed.as.integer = 27, datasources = studies), "'force.output.to.k.decimal.places' must be length 1 or one value per\\s+study") + expect_error(ds.rNorm(samp.size = 10, mean = c(0, 100), sd = 1, newobj = "x", seed.as.integer = 27, datasources = studies), "must have length 1") + expect_error(ds.rNorm(samp.size = 10, mean = 0, sd = c(1, 2), newobj = "x", seed.as.integer = 27, datasources = studies), "must have length 1") + expect_error(ds.rNorm(samp.size = 10, mean = 0, sd = 1, force.output.to.k.decimal.places = c(2, 4), newobj = "x", seed.as.integer = 27, datasources = studies), "must have length 1") expect_length(sent$calls, 0) }) test_that("ds.rNorm checks every study's sd", { sent <- record_server_calls() - res <- ds.rNorm(samp.size = 10, mean = 0, sd = c(1, -1, 1), newobj = "x", seed.as.integer = 27, datasources = studies) + expect_error(ds.rNorm(samp.size = 10, mean = 0, sd = c(1, -1, 1), newobj = "x", seed.as.integer = 27, datasources = studies), "must be greater than 0") - expect_equal(res, "ERROR: sd must be > 0") expect_length(sent$calls, 0) }) @@ -150,15 +148,14 @@ test_that("ds.rPois sends a single lambda to every study", { test_that("ds.rPois rejects lambda with the wrong number of values", { sent <- record_server_calls() - expect_error(ds.rPois(samp.size = 10, lambda = c(1, 50), newobj = "x", seed.as.integer = 27, datasources = studies), "'lambda' must be length 1 or one value per\\s+study") + expect_error(ds.rPois(samp.size = 10, lambda = c(1, 50), newobj = "x", seed.as.integer = 27, datasources = studies), "must have length 1") expect_length(sent$calls, 0) }) test_that("ds.rPois checks every study's lambda", { sent <- record_server_calls() - res <- ds.rPois(samp.size = 10, lambda = c(1, 0, 1), newobj = "x", seed.as.integer = 27, datasources = studies) + expect_error(ds.rPois(samp.size = 10, lambda = c(1, 0, 1), newobj = "x", seed.as.integer = 27, datasources = studies), "must be greater than 0") - expect_equal(res, "ERROR: lambda must be > 0") expect_length(sent$calls, 0) }) @@ -186,17 +183,16 @@ test_that("ds.rUnif sends a single min, max and decimal places to every study", test_that("ds.rUnif rejects min, max or decimal places with the wrong number of values", { sent <- record_server_calls() - expect_error(ds.rUnif(samp.size = 10, min = c(0, 2), max = 10, newobj = "x", seed.as.integer = 27, datasources = studies), "'min' must be length 1 or one value per\\s+study") - expect_error(ds.rUnif(samp.size = 10, min = 0, max = c(2, 5), newobj = "x", seed.as.integer = 27, datasources = studies), "'max' must be length 1 or one value per\\s+study") - expect_error(ds.rUnif(samp.size = 10, min = 0, max = 1, force.output.to.k.decimal.places = c(1, 2), newobj = "x", seed.as.integer = 27, datasources = studies), "'force.output.to.k.decimal.places' must be length 1 or one value per\\s+study") + expect_error(ds.rUnif(samp.size = 10, min = c(0, 2), max = 10, newobj = "x", seed.as.integer = 27, datasources = studies), "must have length 1") + expect_error(ds.rUnif(samp.size = 10, min = 0, max = c(2, 5), newobj = "x", seed.as.integer = 27, datasources = studies), "must have length 1") + expect_error(ds.rUnif(samp.size = 10, min = 0, max = 1, force.output.to.k.decimal.places = c(1, 2), newobj = "x", seed.as.integer = 27, datasources = studies), "must have length 1") expect_length(sent$calls, 0) }) test_that("ds.rUnif checks every study's min and max", { sent <- record_server_calls() - res <- ds.rUnif(samp.size = 10, min = c(0, 5, 0), max = c(1, 2, 1), newobj = "x", seed.as.integer = 27, datasources = studies) + expect_error(ds.rUnif(samp.size = 10, min = c(0, 5, 0), max = c(1, 2, 1), newobj = "x", seed.as.integer = 27, datasources = studies), "must be greater than") - expect_equal(res, "ERROR: max must be greater than min") expect_length(sent$calls, 0) }) diff --git a/tests/testthat/test-disc-ds.table.R b/tests/testthat/test-disc-ds.table.R index 0b7a474d7..7f225aa7f 100644 --- a/tests/testthat/test-disc-ds.table.R +++ b/tests/testthat/test-disc-ds.table.R @@ -98,15 +98,8 @@ test_that("setup", { # context("ds.table::disc::tests::phase 2::table.assign=FALSE") test_that("table disclosure, table.assign=FALSE", { - table.res <- ds.table(rvar='D$GENDER', cvar="D$DIS_AMI", table.assign=FALSE, newobj="new_table3") - - expect_length(table.res, 2) - expect_length(table.res$validity.message, 1) - expect_equal(table.res$validity.message, "All studies failed for reasons identified below", fixed = TRUE) - expect_length(table.res$error.message, 3) - expect_equal(table.res$error.message$sim1, "Failed: at least one cell has a non-zero count less than nfilter.tab i.e. 3", fixed = TRUE) - expect_equal(table.res$error.message$sim2, "Failed: at least one cell has a non-zero count less than nfilter.tab i.e. 3", fixed = TRUE) - expect_equal(table.res$error.message$sim3, "Failed: at least one cell has a non-zero count less than nfilter.tab i.e. 3", fixed = TRUE) + error <- expect_error(ds.table(rvar='D$GENDER', cvar="D$DIS_AMI", table.assign=FALSE, newobj="new_table3"), "All studies failed") + expect_match(conditionMessage(error), "non-zero count less than nfilter.tab") }) # context("ds.table::disc::tests::phase 2::table.assign=TRUE") diff --git a/tests/testthat/test-smk-ds.cor.R b/tests/testthat/test-smk-ds.cor.R index aaa6eaf73..baabb30c4 100644 --- a/tests/testthat/test-smk-ds.cor.R +++ b/tests/testthat/test-smk-ds.cor.R @@ -137,7 +137,7 @@ test_that("ds.cor ignores y with a warning when x is a data.frame", { expect_warning( res.xy <- ds.cor(x = "D", y = "D$survtime", type = "split"), - "y will be ignored", fixed = TRUE + "`y` is ignored", fixed = TRUE ) expect_equal(res.xy, res.x) diff --git a/tests/testthat/test-smk-ds.cov.R b/tests/testthat/test-smk-ds.cov.R index f9ba65690..c9ba84069 100644 --- a/tests/testthat/test-smk-ds.cov.R +++ b/tests/testthat/test-smk-ds.cov.R @@ -102,7 +102,7 @@ test_that("ds.cov ignores y with a warning when x is a data.frame", { expect_warning( res.xy <- ds.cov(x = "D", y = "D$survtime", type = "split"), - "y will be ignored", fixed = TRUE + "`y` is ignored", fixed = TRUE ) expect_equal(res.xy, res.x) diff --git a/tests/testthat/test-smk-ds.lmerSLMA.R b/tests/testthat/test-smk-ds.lmerSLMA.R index 6baafa66a..ce752b164 100644 --- a/tests/testthat/test-smk-ds.lmerSLMA.R +++ b/tests/testthat/test-smk-ds.lmerSLMA.R @@ -51,8 +51,7 @@ test_that("alternative formulae for nested groups", { test_that("server side error", { res = ds.lmerSLMA(formula = 'BMI ~ trtGrp + Male + (1|idSurgery)', dataName = 'D', optimizer = 'nloptwrap') expect_equal(res$Convergence.error.message[2], "Study2: no convergence error reported") - res=ds.lmerSLMA(formula = 'BMI ~ trtGrp + Male + (1|idSurgery)', dataName = 'D', optimizer = 'not_this_one') - expect_equal(res$errorMessage, "ERROR: the only optimizer currently available for lmer is 'nloptwrap', please respecify") + expect_error(ds.lmerSLMA(formula = 'BMI ~ trtGrp + Male + (1|idSurgery)', dataName = 'D', optimizer = 'not_this_one'), "must be \"nloptwrap\"") res = ds.lmerSLMA(formula = 'BMI ~ trtGrp + Male + (1|idDoctor)', dataName = "D", REML = FALSE) expect_equal(res$output.summary$study1$methTitle, "Linear mixed model fit by maximum likelihood ") }) diff --git a/tests/testthat/test-smk-ds.mdPattern.R b/tests/testthat/test-smk-ds.mdPattern.R index 077012c34..aaf113f04 100644 --- a/tests/testthat/test-smk-ds.mdPattern.R +++ b/tests/testthat/test-smk-ds.mdPattern.R @@ -33,7 +33,7 @@ test_that("simple mdPattern, combine", { ) expect_named(res, c("pattern", "valid", "message", "studies")) - expect_true(any(grepl("Disclosure control", caught_warnings))) + expect_true(any(grepl("disclosure control", caught_warnings))) expect_true(is.matrix(res$pattern)) }) @@ -90,7 +90,7 @@ test_that("class consistency check aborts when classes differ across studies", { ds.asDataMatrix(x.name = "D", newobj = "mixed.class", datasources = ds.test_env$connections[1]) ds.assign(toAssign = "D", newobj = "mixed.class", datasources = ds.test_env$connections[2:3]) - expect_error(ds.mdPattern(x = "mixed.class"), "not of the same class in all studies") + expect_error(ds.mdPattern(x = "mixed.class"), "must have the same class in all studies") expect_no_error(ds.mdPattern(x = "mixed.class", classConsistencyCheck = FALSE)) }) diff --git a/tests/testthat/test-smk-ds.rBinom.R b/tests/testthat/test-smk-ds.rBinom.R index 3fecc749f..5f3f14ab6 100644 --- a/tests/testthat/test-smk-ds.rBinom.R +++ b/tests/testthat/test-smk-ds.rBinom.R @@ -64,7 +64,7 @@ test_that("one value per study", { # context("ds.rBinom::smk::wrong number of values") test_that("wrong number of values per study", { - expect_error(ds.rBinom(samp.size = 50, size = c(1, 10), prob = 0.5, newobj = "no.obj", seed.as.integer = 27), "must be length 1 or one value per study") + expect_error(ds.rBinom(samp.size = 50, size = c(1, 10), prob = 0.5, newobj = "no.obj", seed.as.integer = 27), "must have length 1") }) # diff --git a/tests/testthat/test-smk-ds.rNorm.R b/tests/testthat/test-smk-ds.rNorm.R index 1a08b928a..b12f95080 100644 --- a/tests/testthat/test-smk-ds.rNorm.R +++ b/tests/testthat/test-smk-ds.rNorm.R @@ -64,7 +64,7 @@ test_that("one value per study", { # context("ds.rNorm::smk::wrong number of values") test_that("wrong number of values per study", { - expect_error(ds.rNorm(samp.size = 50, mean = c(0, 100), sd = 1, newobj = "no.obj", seed.as.integer = 27), "must be length 1 or one value per study") + expect_error(ds.rNorm(samp.size = 50, mean = c(0, 100), sd = 1, newobj = "no.obj", seed.as.integer = 27), "must have length 1") }) # diff --git a/tests/testthat/test-smk-ds.rPois.R b/tests/testthat/test-smk-ds.rPois.R index 31baf262d..7ad6fad39 100644 --- a/tests/testthat/test-smk-ds.rPois.R +++ b/tests/testthat/test-smk-ds.rPois.R @@ -64,7 +64,7 @@ test_that("one value per study", { # context("ds.rPois::smk::wrong number of values") test_that("wrong number of values per study", { - expect_error(ds.rPois(samp.size = 50, lambda = c(1, 50), newobj = "no.obj", seed.as.integer = 27), "must be length 1 or one value per study") + expect_error(ds.rPois(samp.size = 50, lambda = c(1, 50), newobj = "no.obj", seed.as.integer = 27), "must have length 1") }) # diff --git a/tests/testthat/test-smk-ds.rUnif.R b/tests/testthat/test-smk-ds.rUnif.R index a296dfeeb..80ff2442a 100644 --- a/tests/testthat/test-smk-ds.rUnif.R +++ b/tests/testthat/test-smk-ds.rUnif.R @@ -64,7 +64,7 @@ test_that("one value per study", { # context("ds.rUnif::smk::wrong number of values") test_that("wrong number of values per study", { - expect_error(ds.rUnif(samp.size = 50, min = c(0, 10), max = 30, newobj = "no.obj", seed.as.integer = 27), "must be length 1 or one value per study") + expect_error(ds.rUnif(samp.size = 50, min = c(0, 10), max = 30, newobj = "no.obj", seed.as.integer = 27), "must have length 1") }) # diff --git a/tests/testthat/test-smk-isDefined.R b/tests/testthat/test-smk-isDefined.R index 77ffa32c0..12acc9d51 100644 --- a/tests/testthat/test-smk-isDefined.R +++ b/tests/testthat/test-smk-isDefined.R @@ -39,7 +39,7 @@ test_that("default test, dataframe D", { }) test_that("default test, dataframe E", { - expect_error(isDefined(ds.test_env$connections, "E"), "The input object E is not defined in discordant1, discordant2, discordant3!", fixed=TRUE) + expect_error(isDefined(ds.test_env$connections, "E"), "\"E\" isn't defined in \"discordant1\", \"discordant2\", and \"discordant3\"", fixed=TRUE) }) test_that("default test, dataframe column E$A", { @@ -57,19 +57,19 @@ test_that("default test, dataframe column E$A", { }) test_that("default test, dataframe column D$A", { - expect_error(isDefined(ds.test_env$connections, "D$A"), "The input object D$A is not defined in discordant3!", fixed=TRUE) + expect_error(isDefined(ds.test_env$connections, "D$A"), "\"D$A\" isn't defined in \"discordant3\"", fixed=TRUE) }) test_that("default test, dataframe column D$B", { - expect_error(isDefined(ds.test_env$connections, "D$B"), "The input object D$B is not defined in discordant2!", fixed=TRUE) + expect_error(isDefined(ds.test_env$connections, "D$B"), "\"D$B\" isn't defined in \"discordant2\"", fixed=TRUE) }) test_that("default test, dataframe column D$C", { - expect_error(isDefined(ds.test_env$connections, "D$C"), "The input object D$C is not defined in discordant1!", fixed=TRUE) + expect_error(isDefined(ds.test_env$connections, "D$C"), "\"D$C\" isn't defined in \"discordant1\"", fixed=TRUE) }) test_that("default test, dataframe column D$D", { - expect_error(isDefined(ds.test_env$connections, "D$D"), "The input object D$D is not defined in discordant1, discordant2, discordant3!", fixed=TRUE) + expect_error(isDefined(ds.test_env$connections, "D$D"), "\"D$D\" isn't defined in \"discordant1\", \"discordant2\", and \"discordant3\"", fixed=TRUE) }) test_that("default test, dataframe columns D,D$B", { @@ -85,7 +85,7 @@ test_that("default test, dataframe columns D,D$B", { }) test_that("default test, dataframe columns D$A,D$B", { - expect_error(isDefined(ds.test_env$connections, c("D$A","D$B")), "The input object D$A is not defined in discordant3!", fixed=TRUE) + expect_error(isDefined(ds.test_env$connections, c("D$A","D$B")), "\"D$A\" isn't defined in \"discordant3\"", fixed=TRUE) }) # error.message = FALSE @@ -209,7 +209,7 @@ test_that("error.message=TRUE test, dataframe D", { }) test_that("error.message=TRUE test, dataframe E", { - expect_error(isDefined(ds.test_env$connections, "E", error.message = TRUE), "The input object E is not defined in discordant1, discordant2, discordant3!", fixed=TRUE) + expect_error(isDefined(ds.test_env$connections, "E", error.message = TRUE), "\"E\" isn't defined in \"discordant1\", \"discordant2\", and \"discordant3\"", fixed=TRUE) }) test_that("error.message=TRUE test, dataframe column E$A", { @@ -227,19 +227,19 @@ test_that("error.message=TRUE test, dataframe column E$A", { }) test_that("error.message=TRUE test, dataframe column D$A", { - expect_error(isDefined(ds.test_env$connections, "D$A", error.message = TRUE), "The input object D$A is not defined in discordant3!", fixed=TRUE) + expect_error(isDefined(ds.test_env$connections, "D$A", error.message = TRUE), "\"D$A\" isn't defined in \"discordant3\"", fixed=TRUE) }) test_that("error.message=TRUE test, dataframe column D$B", { - expect_error(isDefined(ds.test_env$connections, "D$B", error.message = TRUE), "The input object D$B is not defined in discordant2!", fixed=TRUE) + expect_error(isDefined(ds.test_env$connections, "D$B", error.message = TRUE), "\"D$B\" isn't defined in \"discordant2\"", fixed=TRUE) }) test_that("error.message=TRUE test, dataframe column D$C", { - expect_error(isDefined(ds.test_env$connections, "D$C", error.message = TRUE), "The input object D$C is not defined in discordant1!", fixed=TRUE) + expect_error(isDefined(ds.test_env$connections, "D$C", error.message = TRUE), "\"D$C\" isn't defined in \"discordant1\"", fixed=TRUE) }) test_that("error.message=TRUE test, dataframe column D$D", { - expect_error(isDefined(ds.test_env$connections, "D$D", error.message = TRUE), "The input object D$D is not defined in discordant1, discordant2, discordant3!", fixed=TRUE) + expect_error(isDefined(ds.test_env$connections, "D$D", error.message = TRUE), "\"D$D\" isn't defined in \"discordant1\", \"discordant2\", and \"discordant3\"", fixed=TRUE) }) test_that("error.message=TRUE test, dataframe columns D,D$B", { @@ -255,7 +255,7 @@ test_that("error.message=TRUE test, dataframe columns D,D$B", { }) test_that("error.message=TRUE test, dataframe columns D$A,D$B", { - expect_error(isDefined(ds.test_env$connections, c("D$A","D$B"), error.message=TRUE), "The input object D$A is not defined in discordant3!", fixed=TRUE) + expect_error(isDefined(ds.test_env$connections, c("D$A","D$B"), error.message=TRUE), "\"D$A\" isn't defined in \"discordant3\"", fixed=TRUE) }) #