diff --git a/NAMESPACE b/NAMESPACE index 646eb7478..8649c76d7 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -120,10 +120,12 @@ export(ds.vectorCalc) import(DSI) import(data.table) importFrom(DSI,datashield.connections_find) -importFrom(cli,cli_abort) -importFrom(cli,cli_inform) -importFrom(cli,cli_verbatim) -importFrom(cli,cli_warn) +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 743263532..c0314feb5 100644 --- a/R/ds.Boole.R +++ b/R/ds.Boole.R @@ -113,7 +113,7 @@ ds.Boole<-function(V1=NULL, V2=NULL, Boolean.operator=NULL, numeric.output=TRUE, .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 '!=' - .checkArgProvided(Boolean.operator, "a Boolean operator in character format, such as '==' or '>='") + .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")){ @@ -151,7 +151,7 @@ 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 diff --git a/R/ds.asFactor.R b/R/ds.asFactor.R index 023eb49cf..9e1a99871 100644 --- a/R/ds.asFactor.R +++ b/R/ds.asFactor.R @@ -195,7 +195,8 @@ ds.asFactor <- function(input.var.name=NULL, newobj.name=NULL, forced.factor.lev # 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 @@ -215,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 aecc10265..1bcc0d6f2 100644 --- a/R/ds.asFactorSimple.R +++ b/R/ds.asFactorSimple.R @@ -31,7 +31,8 @@ ds.asFactorSimple <- function(input.var.name=NULL, newobj.name=NULL, datasources # 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.boxPlot.R b/R/ds.boxPlot.R index 5a1da5bd8..68ea8fc76 100644 --- a/R/ds.boxPlot.R +++ b/R/ds.boxPlot.R @@ -100,7 +100,7 @@ ds.boxPlot <- function(x, variables = NULL, group = NULL, group2 = NULL, xlabel 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.cbind.R b/R/ds.cbind.R index 5209b37b7..1c44c4559 100644 --- a/R/ds.cbind.R +++ b/R/ds.cbind.R @@ -146,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)){ @@ -154,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]}}.") } } } @@ -169,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 1ac677b1e..2cf9adddc 100644 --- a/R/ds.changeRefGroup.R +++ b/R/ds.changeRefGroup.R @@ -122,7 +122,7 @@ ds.changeRefGroup <- function(x=NULL, ref=NULL, newobj=NULL, reorderByRef=FALSE, 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.contourPlot.R b/R/ds.contourPlot.R index fcae19b2c..a73182683 100644 --- a/R/ds.contourPlot.R +++ b/R/ds.contourPlot.R @@ -211,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) @@ -406,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){ diff --git a/R/ds.cor.R b/R/ds.cor.R index d79848931..be2b991fa 100644 --- a/R/ds.cor.R +++ b/R/ds.cor.R @@ -99,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"){ diff --git a/R/ds.cov.R b/R/ds.cov.R index 15b4f1181..b3115633e 100644 --- a/R/ds.cov.R +++ b/R/ds.cov.R @@ -116,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"){ diff --git a/R/ds.dataFrame.R b/R/ds.dataFrame.R index 802917b63..a26145438 100644 --- a/R/ds.dataFrame.R +++ b/R/ds.dataFrame.R @@ -124,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)){ @@ -132,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]}}.") } } } @@ -147,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.dataFrameSubset.R b/R/ds.dataFrameSubset.R index a4452fd08..fb03be8d5 100644 --- a/R/ds.dataFrameSubset.R +++ b/R/ds.dataFrameSubset.R @@ -120,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)) @@ -136,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)) @@ -146,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)) @@ -217,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 6b96cc69c..9fe581127 100644 --- a/R/ds.densityGrid.R +++ b/R/ds.densityGrid.R @@ -133,7 +133,7 @@ ds.densityGrid <- function(x=NULL, y=NULL, numints=20, type='combine', datasourc # 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) @@ -141,8 +141,6 @@ 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"){ @@ -157,7 +155,7 @@ ds.densityGrid <- function(x=NULL, y=NULL, numints=20, type='combine', datasourc # 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{ diff --git a/R/ds.dmtC2S.R b/R/ds.dmtC2S.R index c520aea0c..c8a5fa32e 100644 --- a/R/ds.dmtC2S.R +++ b/R/ds.dmtC2S.R @@ -82,7 +82,8 @@ if(dplyr::is.tbl(dfdata)) if(!is.matrix(dfdata) && !is.data.frame(dfdata) && !dplyr::is.tbl(dfdata)) { - cli_abort("{.arg dfdata} must be a data.frame, matrix or tibble.") + 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 e66daec45..696c0765a 100644 --- a/R/ds.elspline.R +++ b/R/ds.elspline.R @@ -35,7 +35,7 @@ ds.elspline <- function(x, n, marginal = FALSE, names = NULL, newobj = NULL, dat .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 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 094683277..bfcb1d021 100644 --- a/R/ds.gamlss.R +++ b/R/ds.gamlss.R @@ -153,7 +153,7 @@ 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}.") } newobj <- .resolveNewobjName(newobj, 'gamlss_res') diff --git a/R/ds.getWGSR.R b/R/ds.getWGSR.R index cebf04496..0f6300d58 100644 --- a/R/ds.getWGSR.R +++ b/R/ds.getWGSR.R @@ -117,12 +117,13 @@ ds.getWGSR <- function(sex=NULL, firstPart=NULL, secondPart=NULL, index=NULL, st # 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 diff --git a/R/ds.glm.R b/R/ds.glm.R index 2c068376c..1534de5f1 100644 --- a/R/ds.glm.R +++ b/R/ds.glm.R @@ -329,7 +329,7 @@ ds.glm <- function(formula=NULL, data=NULL, family=NULL, offset=NULL, weights=NU # 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 - .warnOffsetInFormula(formula) + .checkOffsetInFormula(formula) formula <- stats::as.formula(formula) @@ -338,7 +338,7 @@ ds.glm <- function(formula=NULL, data=NULL, family=NULL, offset=NULL, weights=NU # 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{ @@ -449,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) @@ -490,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. @@ -528,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, @@ -752,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.glmSLMA.R b/R/ds.glmSLMA.R index 239cf1ac7..19f3515a7 100644 --- a/R/ds.glmSLMA.R +++ b/R/ds.glmSLMA.R @@ -377,7 +377,7 @@ ds.glmSLMA<-function(formula=NULL, family=NULL, offset=NULL, weights=NULL, combi # 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 - .warnOffsetInFormula(formula) + .checkOffsetInFormula(formula) formula <- stats::as.formula(formula) @@ -429,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) @@ -539,13 +539,7 @@ if(!at.least.one.study.valid) #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) @@ -572,7 +566,7 @@ if(at.least.one.study.data.error) 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) @@ -619,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]]))) } } } @@ -761,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 401c16be1..7e57cedcb 100644 --- a/R/ds.glmSummary.R +++ b/R/ds.glmSummary.R @@ -83,7 +83,8 @@ ds.glmSummary <- function(x.name, newobj=NULL, datasources=NULL) { # 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 diff --git a/R/ds.glmerSLMA.R b/R/ds.glmerSLMA.R index 0dfe036a5..455c105f5 100644 --- a/R/ds.glmerSLMA.R +++ b/R/ds.glmerSLMA.R @@ -254,7 +254,7 @@ ds.glmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.m # 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 - .warnOffsetInFormula(formula) + .checkOffsetInFormula(formula) formula <- stats::as.formula(formula) @@ -263,7 +263,7 @@ ds.glmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.m # 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) @@ -300,7 +300,7 @@ ds.glmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.m if(!is.null(control_type) && is.null(control_value)) { - cli_abort(c("{.arg control_value} must be set when {.arg control_type} is set.", "i" = "For example, {.code control_value = 1.0e-7}.")) + 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)) @@ -333,7 +333,7 @@ ds.glmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.m 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, @@ -377,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]]))) } } } @@ -395,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.")) } } @@ -521,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)) } @@ -585,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 645b76764..804fc941e 100644 --- a/R/ds.heatmapPlot.R +++ b/R/ds.heatmapPlot.R @@ -259,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) @@ -458,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){ diff --git a/R/ds.histogram.R b/R/ds.histogram.R index 9737dcc4b..9d4895f11 100644 --- a/R/ds.histogram.R +++ b/R/ds.histogram.R @@ -208,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 @@ -254,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="")) } @@ -265,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="")) } diff --git a/R/ds.isNA.R b/R/ds.isNA.R index c6e5b1ed2..5083485e8 100644 --- a/R/ds.isNA.R +++ b/R/ds.isNA.R @@ -79,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.kurtosis.R b/R/ds.kurtosis.R index 95ef39802..52c58825f 100644 --- a/R/ds.kurtosis.R +++ b/R/ds.kurtosis.R @@ -34,7 +34,7 @@ ds.kurtosis <- function(x=NULL, method=1, type='both', datasources=NULL, classCo .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 @@ -63,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.lexis.R b/R/ds.lexis.R index 74aaf3b80..c7042b09b 100644 --- a/R/ds.lexis.R +++ b/R/ds.lexis.R @@ -215,8 +215,9 @@ ds.lexis<-function(data=NULL, intervalWidth=NULL, idCol=NULL, entryCol=NULL, exi .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.lmerSLMA.R b/R/ds.lmerSLMA.R index 5c42ab342..9b1f73a87 100644 --- a/R/ds.lmerSLMA.R +++ b/R/ds.lmerSLMA.R @@ -213,7 +213,7 @@ ds.lmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.me # 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 - .warnOffsetInFormula(formula) + .checkOffsetInFormula(formula) formula <- stats::as.formula(formula) @@ -222,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) @@ -246,7 +246,7 @@ ds.lmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.me if(!is.null(control_type) && is.null(control_value)) { - cli_abort(c("{.arg control_value} must be set when {.arg control_type} is set.", "i" = "For example, {.code control_value = 1.0e-7}.")) + 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)) @@ -277,7 +277,7 @@ ds.lmerSLMA <- function(formula=NULL, offset=NULL, weights=NULL, combine.with.me 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, @@ -317,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]]))) } } } @@ -335,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.")) } } @@ -462,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)) } @@ -526,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.mdPattern.R b/R/ds.mdPattern.R index 4418641b5..e9c974269 100644 --- a/R/ds.mdPattern.R +++ b/R/ds.mdPattern.R @@ -143,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 @@ -158,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] }) diff --git a/R/ds.metadata.R b/R/ds.metadata.R index 96846d41c..27bcf8e03 100644 --- a/R/ds.metadata.R +++ b/R/ds.metadata.R @@ -60,7 +60,8 @@ ds.metadata = function(x=NULL, datasources=NULL) ##################################################################################### #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.quantileMean.R b/R/ds.quantileMean.R index 2702c8879..e0496e005 100644 --- a/R/ds.quantileMean.R +++ b/R/ds.quantileMean.R @@ -108,7 +108,7 @@ 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"){ diff --git a/R/ds.rBinom.R b/R/ds.rBinom.R index c1b41eff1..2863b865b 100644 --- a/R/ds.rBinom.R +++ b/R/ds.rBinom.R @@ -139,7 +139,7 @@ if(is.numeric(size)){ } if(!size.valid){ -cli_abort("{.arg size} must be greater than 0.") +cli_abort("{.arg size} must be greater than 0, not {.val {unique(size[size <= 0])}}.") } prob.valid<-1 @@ -150,7 +150,7 @@ if(is.numeric(prob)){ } if(!prob.valid){ -cli_abort("{.arg prob} must be between 0 and 1.") +cli_abort("{.arg prob} must be between 0 and 1, not {.val {unique(prob[prob <= 0 | prob >= 1])}}.") } @@ -181,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 0aeec29af..ff40b3d95 100644 --- a/R/ds.rNorm.R +++ b/R/ds.rNorm.R @@ -151,7 +151,7 @@ if(is.numeric(sd)){ } if(!sd.valid){ -cli_abort("{.arg sd} must be greater than 0.") +cli_abort("{.arg sd} must be greater than 0, not {.val {unique(sd[sd <= 0])}}.") } decimal.places.valid<-1 @@ -160,7 +160,7 @@ decimal.places.valid<-0 } if(!decimal.places.valid){ -cli_abort("{.arg force.output.to.k.decimal.places} must be an integer between 0 and 9.") +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])}}.") } ################################################################################### @@ -189,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 1b85d82c3..167c956da 100644 --- a/R/ds.rPois.R +++ b/R/ds.rPois.R @@ -131,7 +131,7 @@ if(is.numeric(lambda)){ } if(!lambda.valid){ -cli_abort("{.arg lambda} must be greater than 0.") +cli_abort("{.arg lambda} must be greater than 0, not {.val {unique(lambda[lambda <= 0])}}.") } ################################################################################### @@ -160,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 3f047a2eb..52bab445d 100644 --- a/R/ds.rUnif.R +++ b/R/ds.rUnif.R @@ -162,7 +162,7 @@ if(is.numeric(min) && is.numeric(max)){ } if(!minmax.valid){ -cli_abort("{.arg max} must be greater than {.arg min}.") +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 @@ -171,7 +171,7 @@ decimal.places.valid<-0 } if(!decimal.places.valid){ -cli_abort("{.arg force.output.to.k.decimal.places} must be an integer between 0 and 9.") +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])}}.") } @@ -203,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 af5086bde..618867822 100644 --- a/R/ds.rbind.R +++ b/R/ds.rbind.R @@ -115,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)) @@ -126,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 { @@ -134,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 f19f2930d..26156d1ff 100644 --- a/R/ds.reShape.R +++ b/R/ds.reShape.R @@ -87,7 +87,8 @@ ds.reShape <- function(data.name=NULL, varying=NULL, v.names=NULL, timevar.name= .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 1fb3d5dff..47b342f21 100644 --- a/R/ds.recodeValues.R +++ b/R/ds.recodeValues.R @@ -86,28 +86,27 @@ ds.recodeValues <- function(var.name=NULL, values2replace.vector=NULL, new.value # 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)){ diff --git a/R/ds.replaceNA.R b/R/ds.replaceNA.R index a502ccc8e..bd21cbbaf 100644 --- a/R/ds.replaceNA.R +++ b/R/ds.replaceNA.R @@ -99,7 +99,8 @@ ds.replaceNA <- function(x=NULL, forNA=NULL, newobj=NULL, datasources=NULL){ # check if replacement values have been provided .checkArgProvided(forNA, "a list of replacement values") if(length(forNA) != length(datasources)){ - cli_abort("{.arg forNA} must have one element per study.") + 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)){ @@ -109,8 +110,8 @@ 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.")) } } @@ -118,7 +119,7 @@ ds.replaceNA <- function(x=NULL, forNA=NULL, newobj=NULL, datasources=NULL){ # 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.rowColCalc.R b/R/ds.rowColCalc.R index 629e1575a..ed792283b 100644 --- a/R/ds.rowColCalc.R +++ b/R/ds.rowColCalc.R @@ -74,9 +74,7 @@ ds.rowColCalc <- function(x=NULL, operation=NULL, newobj=NULL, datasources=NULL) 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)){ .abortInvalidChoice("operation", ops) diff --git a/R/ds.sample.R b/R/ds.sample.R index 422d9e264..cb67fd100 100644 --- a/R/ds.sample.R +++ b/R/ds.sample.R @@ -139,7 +139,7 @@ ds.sample<-function(x=NULL, size=NULL, seed.as.integer=NULL, replace=FALSE, pro # matrix or data.frame on the serverside if(is.character(x)&&is.null(size)){ - cli_abort("{.arg size} must be an integer that sets how many records to sample.") + 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 @@ -174,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.seq.R b/R/ds.seq.R index e6a0cad52..0e597b254 100644 --- a/R/ds.seq.R +++ b/R/ds.seq.R @@ -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){ - cli_abort(c("{.arg FROM.value.char} must be a real number in inverted commas.", "i" = "For example, {.val -3.7} or {.val 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){ - cli_abort(c("{.arg TO.value.char} must be a real number in inverted commas.", "i" = "For example, {.val -3.7} or {.val 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){ - cli_abort(c("{.arg BY.value.char} must be a real number in inverted commas.", "i" = "For example, {.val 5} or {.val -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,14 +163,16 @@ 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){ - cli_abort(c("{.arg LENGTH.OUT.value.char} must be an integer in inverted commas.", "i" = "For example, {.val 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))){ - cli_abort("{.arg ALONG.WITH.name} must be the name of a server-side 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 diff --git a/R/ds.skewness.R b/R/ds.skewness.R index 324f05109..46e3b1d9f 100644 --- a/R/ds.skewness.R +++ b/R/ds.skewness.R @@ -86,7 +86,7 @@ ds.skewness <- function(x=NULL, method=1, type='both', datasources=NULL, classCo .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 @@ -114,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.summary.R b/R/ds.summary.R index d6824a740..ea3f2080f 100644 --- a/R/ds.summary.R +++ b/R/ds.summary.R @@ -77,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 88cc23322..75c4d8631 100644 --- a/R/ds.table.R +++ b/R/ds.table.R @@ -197,11 +197,13 @@ ds.table <- function(rvar=NULL, cvar=NULL, stvar=NULL, report.chisq.tests=FALSE, .checkArgProvided(rvar, "a character string that names the row variable") if(!is.null(cvar)&&!is.character(cvar)){ - cli_abort("{.arg cvar} must be a character string that names the column variable.") + 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)){ - cli_abort("{.arg stvar} must be a character string that names the variable that codes the separate tables.") + 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"){ @@ -209,7 +211,8 @@ ds.table <- function(rvar=NULL, cvar=NULL, stvar=NULL, report.chisq.tests=FALSE, } if(!is.null(force.nfilter)&&!is.character(force.nfilter)){ - cli_abort("{.arg force.nfilter} must be a character string that specifies an integer.") + supplied <- .describeSupplied(force.nfilter) + cli_abort("{.arg force.nfilter} must be a character string that specifies an integer, not {supplied}.") } @@ -270,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)) @@ -292,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)) @@ -316,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)) @@ -463,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") } } @@ -490,7 +492,9 @@ if(numsources>1) if(table.dimensions[ns]!=table.dimensions[ns+1]) { all.dims.same<-FALSE - cli_abort(c("Tables in different sources have different numbers of dimensions.", "i" = "Analyse and combine them yourself from the study-specific tables.")) + 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.")) } } @@ -706,7 +710,7 @@ for(oo in 1:length(table.current.study[,1])) if(d1.a!=d1||d2.a!=d2||d3.a!=d3) { - cli_abort(c("Table dimensions differ across studies.", "i" = "Check the data in each study and calculate counts and percentages yourself from the counts in each study.")) + 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 @@ -925,7 +929,7 @@ for(oo in 1:length(table.current.study[,1])) if(d1.a!=d1||d2.a!=d2) { - cli_abort(c("Table dimensions differ across studies.", "i" = "Check the data in each study and calculate counts and percentages yourself from the counts in each study.")) + 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 @@ -1117,7 +1121,7 @@ for(oo in 1:length(table.current.study[,1])) if(d1.a!=d1) { - cli_abort(c("Table dimensions differ across studies.", "i" = "Check the data in each study and calculate counts and percentages yourself from the counts in each study.")) + 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 0ca7829ed..b7c842dcc 100644 --- a/R/ds.tapply.R +++ b/R/ds.tapply.R @@ -134,12 +134,12 @@ ds.tapply <- function(X.name=NULL, INDEX.names=NULL, FUN.name=NULL, datasources= ###INDEX.names # check if user has provided the name of the column(s) that holds INDEX.names if(is.null(INDEX.names)){ - cli_abort("{.arg INDEX.names} must name a single factor or a list of factors, in inverted commas.") + 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 diff --git a/R/ds.tapply.assign.R b/R/ds.tapply.assign.R index 9438b21a9..d799f1355 100644 --- a/R/ds.tapply.assign.R +++ b/R/ds.tapply.assign.R @@ -139,12 +139,12 @@ ds.tapply.assign <- function(X.name=NULL, INDEX.names=NULL, FUN.name=NULL, newob ###INDEX.names # check if user has provided the name of the column(s) that holds INDEX.names if(is.null(INDEX.names)){ - cli_abort("{.arg INDEX.names} must name a single factor or a list of factors, in inverted commas.") + 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 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 6544bee2c..e3976dfcd 100644 --- a/R/utils.R +++ b/R/utils.R @@ -23,7 +23,10 @@ .verifyDatasources <- function(datasources, call = parent.frame()) { isConnectionClass <- vapply(datasources, function(x) inherits(unlist(x), "DSConnection"), logical(1)) if (!all(isConnectionClass)) { - cli_abort("{.arg datasources} must be a list of {.cls DSConnection} objects.", call = call) + 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) } } @@ -61,12 +64,26 @@ classes <- lapply(results, function(r) r[[field]]) if (length(unique(lapply(classes, sort))) > 1) { if (is.null(objectName)) { - cli_abort("The input object must have the same class in all studies.", call = call) + cli_abort(c("The input object must have the same class in all studies.", .describeStudyClasses(classes)), call = call) } - cli_abort("{.val {objectName}} must have the same class in all studies.", 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 @@ -81,7 +98,8 @@ #' @noRd .checkNewobjName <- function(newobj, call = parent.frame()) { if (!is.character(newobj) || length(newobj) != 1) { - cli_abort("{.arg newobj} must be a single character string.", call = call) + 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) } } @@ -134,8 +152,12 @@ #' @noRd .checkArgsSet <- function(..., call = parent.frame()) { values <- list(...) - if (any(vapply(values, is.null, logical(1)))) { - cli_abort("{.arg {names(values)}} must all be set.", call = call) + 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) } } @@ -152,24 +174,31 @@ return("NULL") } if (!is.numeric(seed.as.integer)) { - cli_abort("{.arg seed.as.integer} must be an integer or {.code NULL}.", call = call) + 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)) } -#' Warn About an Offset or Weights Written Into a Model Formula +#' Check That a Model Formula Has No Offset or Weights Term +#' +#' The server rejects function calls inside a formula, so an `offset()` or +#' `weights()` term always fails there. #' #' @param formula The model formula, as a character string or formula. -#' @param call The frame to report the warning from. -#' @importFrom cli cli_warn -#' @return Invisibly returns `NULL`. Called for its side effect. +#' @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 -.warnOffsetInFormula <- function(formula, call = parent.frame()) { - if (any(grepl("offset|weights", formula, ignore.case = TRUE))) { - cli_warn(c( - "You may have specified an offset or regression weights in the model formula.", - "i" = "Specify them separately with the {.arg offset} and {.arg weights} arguments." +.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) } } @@ -186,8 +215,10 @@ .checkObjectClasses <- function(datasources, x, call = parent.frame()) { allowed <- c("data.frame", "matrix", "numeric", "integer", "character", "factor", "logical") for (name in x) { - if (!any(allowed %in% checkClass(datasources, name))) { - cli_abort("Each object must be of class {.or {.val {allowed}}}.", call = call) + 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) } } } @@ -205,14 +236,14 @@ #' @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) %in% c("data.frame", "matrix")), logical(1)) + 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 study {j} are duplicated, so a suffix {.val .k} is added to the kth replicate.", call = call) + 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]]) { @@ -221,21 +252,25 @@ as.numeric(ds.length(x[i], type = "split", datasources = study)[[1]]) }, numeric(1)) if (any(rows != rows[1])) { - cli_abort("All components must have the same number of rows.", call = call) + 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. +#' @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. +#' @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()) { - cli_abort("{.arg {argName}} must be {.or {.val {choices}}}.", call = call) + 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 @@ -256,7 +291,25 @@ return(rep(values, numStudies)) } if (length(values) != numStudies) { - cli_abort("{.arg {argName}} must have length 1 or one value per study.", call = call) + 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 index 1586c8e0c..f50643088 100644 --- a/tests/testthat/test-_-utils.R +++ b/tests/testthat/test-_-utils.R @@ -12,9 +12,14 @@ test_that(".checkArgProvided names the argument and reports the calling function }) # context("utils::.abortInvalidChoice") -test_that(".abortInvalidChoice lists the allowed values", { - expect_error(.abortInvalidChoice("type", c("combine", "split")), "`type` must be \"combine\" or \"split\"") - expect_error(.abortInvalidChoice("type", c("both", "combine", "split")), "`type` must be \"both\", \"combine\", or \"split\"") +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") @@ -26,11 +31,14 @@ test_that(".resolveNewobjName applies the default before validating", { 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") @@ -41,6 +49,7 @@ test_that(".checkClassConsistency compares the chosen field across studies", { 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") @@ -48,17 +57,21 @@ test_that(".seedAsText converts the seed and rejects anything that isn't a numbe 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::.warnOffsetInFormula") -test_that(".warnOffsetInFormula looks for an offset or weights in the formula", { - expect_no_warning(.warnOffsetInFormula("y~x")) - expect_warning(.warnOffsetInFormula("y~offset(x)"), "offset or regression weights") - expect_warning(.warnOffsetInFormula("y~x+WEIGHTS"), "offset or regression weights") +# 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 eecb996c3..ad828e875 100644 --- a/tests/testthat/test-arg-ds.Boole.R +++ b/tests/testthat/test-arg-ds.Boole.R @@ -25,7 +25,7 @@ test_that("Boole_erros", { 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"), "An unrecognized Boolean operator, AA, has provide", 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.asFactor.R b/tests/testthat/test-arg-ds.asFactor.R index 5f433fdcb..7e5467898 100644 --- a/tests/testthat/test-arg-ds.asFactor.R +++ b/tests/testthat/test-arg-ds.asFactor.R @@ -22,8 +22,8 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.asFactor::arg::test errors") test_that("asFactor_erros", { expect_error(ds.asFactor(), "must be the name of the variable to convert", 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(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.cbind.R b/tests/testthat/test-arg-ds.cbind.R index d32131c3d..75c15051e 100644 --- a/tests/testthat/test-arg-ds.cbind.R +++ b/tests/testthat/test-arg-ds.cbind.R @@ -24,7 +24,7 @@ test_that("cbind_erros", { ds.asList(x='D$LAB_TSC', newobj="as_list") 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), "Each object must be of class", 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.dataFrame.R b/tests/testthat/test-arg-ds.dataFrame.R index 1f966e4f1..bec04a8a6 100644 --- a/tests/testthat/test-arg-ds.dataFrame.R +++ b/tests/testthat/test-arg-ds.dataFrame.R @@ -24,7 +24,7 @@ test_that("dataframe_erros", { 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), "Each object must be of class", 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 a6a6d43ca..af8626970 100644 --- a/tests/testthat/test-arg-ds.dataFrameSubset.R +++ b/tests/testthat/test-arg-ds.dataFrameSubset.R @@ -33,17 +33,17 @@ test_that("dataFrameSubset_erros", { # 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.gamlss.R b/tests/testthat/test-arg-ds.gamlss.R index 609c281c4..20e4908f7 100644 --- a/tests/testthat/test-arg-ds.gamlss.R +++ b/tests/testthat/test-arg-ds.gamlss.R @@ -23,7 +23,7 @@ connect.studies.dataset.gamlss(list("e3_bw", "e3_gac_None")) test_that("gamlss_errors", { 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), "Provide the name of the explanatory variable in 'xvar' argument", 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 e4221bbcd..f54c4721a 100644 --- a/tests/testthat/test-arg-ds.glm.R +++ b/tests/testthat/test-arg-ds.glm.R @@ -25,6 +25,11 @@ test_that("glm_errors", { 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) +}) + # # Done # diff --git a/tests/testthat/test-arg-ds.kurtosis.R b/tests/testthat/test-arg-ds.kurtosis.R index 677fb2c55..48ddec0e9 100644 --- a/tests/testthat/test-arg-ds.kurtosis.R +++ b/tests/testthat/test-arg-ds.kurtosis.R @@ -29,8 +29,8 @@ test_that("setup", { test_that("kurtosis_erros", { 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 an integer between 1 and 3", fixed=TRUE) - expect_error(ds.kurtosis(x='D$LAB_TSC', method="4"), "must be an integer between 1 and 3", 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.lexis.R b/tests/testthat/test-arg-ds.lexis.R index c0f5ca66d..04133e4e0 100644 --- a/tests/testthat/test-arg-ds.lexis.R +++ b/tests/testthat/test-arg-ds.lexis.R @@ -26,12 +26,12 @@ test_that("lexis_erros", { # 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.reShape.R b/tests/testthat/test-arg-ds.reShape.R index 288f98625..4a7084227 100644 --- a/tests/testthat/test-arg-ds.reShape.R +++ b/tests/testthat/test-arg-ds.reShape.R @@ -22,9 +22,9 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.reShape::arg::test errors") test_that("reShape_erros", { 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 character string", fixed=TRUE) - expect_error(ds.reShape(data.name="test", sep=""), "must be a character string", fixed=TRUE) - expect_error(ds.reShape(data.name="test", sep="ts"), "must be a character string", 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 2bb7fd902..ab2d89e16 100644 --- a/tests/testthat/test-arg-ds.recodeValues.R +++ b/tests/testthat/test-arg-ds.recodeValues.R @@ -22,12 +22,12 @@ connect.studies.dataset.cnsim(list("LAB_TSC")) # context("ds.recodeValues::arg::test errors") test_that("recodeValues_erros", { expect_error(ds.recodeValues(), "must be the name of the variable to recode", 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('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.rowColCalc.R b/tests/testthat/test-arg-ds.rowColCalc.R index a5a473f64..8077d1a27 100644 --- a/tests/testthat/test-arg-ds.rowColCalc.R +++ b/tests/testthat/test-arg-ds.rowColCalc.R @@ -22,7 +22,7 @@ connect.studies.dataset.cnsim(list("LAB_TSC", "LAB_HDL")) # context("ds.rowColCalc::arg::test errors") test_that("rowColCalc_errors", { 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' = NULL. Please set it to 'rowSums', 'colSums', 'rowMeans' or 'colMeans'", 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.skewness.R b/tests/testthat/test-arg-ds.skewness.R index 070d551d6..848589510 100644 --- a/tests/testthat/test-arg-ds.skewness.R +++ b/tests/testthat/test-arg-ds.skewness.R @@ -29,8 +29,8 @@ test_that("setup", { test_that("skewness_erros", { 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 an integer between 1 and 3", fixed=TRUE) - expect_error(ds.skewness(x='D$LAB_TSC', method="4"), "must be an integer between 1 and 3", 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-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 afea544d1..d12cff631 100644 --- a/tests/testthat/test-arg-per-study-arguments.R +++ b/tests/testthat/test-arg-per-study-arguments.R @@ -11,7 +11,7 @@ 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) @@ -37,7 +37,7 @@ test_that(".expandToStudies keeps one value per study", { }) test_that(".expandToStudies rejects any other length", { - expect_error(.expandToStudies(c(1, 2), "x", 3), "must have length 1") + 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") }) 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.mdPattern.R b/tests/testthat/test-smk-ds.mdPattern.R index 570068458..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)) }) 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) }) #