| 1 |
# Promise helpers taken from: |
| 2 |
# https://github.com/rstudio/promises/blob/main/tests/testthat/common.R |
| 3 |
# Block until all pending later tasks have executed |
| 4 |
wait_for_it <- function() { |
| 5 |
while (!later::loop_empty()) { |
| 6 |
later::run_now(0.1) |
| 7 |
} |
| 8 |
} |
| 9 |
|
| 10 |
# Block until the promise is resolved/rejected. If resolved, return the value. |
| 11 |
# If rejected, throw (yes throw, not return) the error. |
| 12 |
extract <- function(promise) { |
| 13 |
promise_value <- NULL |
| 14 |
error <- NULL |
| 15 |
promise %...>% |
| 16 |
(function(value) promise_value <<- value) %...!% |
| 17 |
(function(reason) error <<- reason) |
| 18 |
|
| 19 |
wait_for_it() |
| 20 |
if (!is.null(error)) |
| 21 |
stop(error) |
| 22 |
else |
| 23 |
promise_value |
| 24 |
} |
| 25 |
|
| 26 |
# TODO: is there a way to get this behavior without exporting these functions? R6? |
| 27 |
# TODO: clientData is documented as a reactiveValues, which this is not. Is it possible that |
| 28 |
# users are currently assigning into clientData? That would not work as expected here. |
| 29 |
#' @noRd |
| 30 |
#' @export |
| 31 |
`$.mockclientdata` <- function(x, name) { |
| 32 |
if (name == "pixelratio") { return(1) } |
| 33 |
if (name == "url_protocol") { return("http:") } |
| 34 |
if (name == "url_hostname") { return("mocksession") } |
| 35 |
if (name == "url_port") { return(1234) } |
| 36 |
if (name == "url_pathname") { return("/mockpath") } |
| 37 |
if (name == "url_hash") { return("#mockhash") } |
| 38 |
if (name == "url_hash_initial") { return("#mockhash") } |
| 39 |
if (name == "url_search") { return("?mocksearch=1") } |
| 40 |
|
| 41 |
clientRE <- "^output_(.+)_([^_]+)$" |
| 42 |
if(grepl(clientRE, name)) { |
| 43 |
# TODO: use proper regex group matching here instead of redundantly parsing |
| 44 |
el <- sub(clientRE, "\\1", name) |
| 45 |
att <- sub(clientRE, "\\2", name) |
| 46 |
|
| 47 |
if (att == "width") { |
| 48 |
return(600) |
| 49 |
} else if (att == "height") { |
| 50 |
return(400) |
| 51 |
} else if (att == "hidden") { |
| 52 |
return(FALSE) |
| 53 |
} |
| 54 |
} |
| 55 |
warning("Unexpected clientdata attribute accessed: ", name) |
| 56 |
return(NULL) |
| 57 |
} |
| 58 |
|
| 59 |
#' @noRd |
| 60 |
#' @export |
| 61 |
`[[.mockclientdata` <- `$.mockclientdata` |
| 62 |
|
| 63 |
#' @noRd |
| 64 |
#' @export |
| 65 |
`[.mockclientdata` <- function(values, name) { |
| 66 |
stop("Single-bracket indexing of mockclientdata is not allowed.") |
| 67 |
} |
| 68 |
|
| 69 |
#' @noRd |
| 70 |
mapNames <- function(func, vals) { |
| 71 |
names(vals) <- vapply(names(vals), func, character(1)) |
| 72 |
vals |
| 73 |
} |
| 74 |
|
| 75 |
#' Returns a noop implementation of the public method `name` of ShinySession. |
| 76 |
#' @include shiny.R |
| 77 |
#' @noRd |
| 78 |
makeNoop <- function(name, msg = paste0(name, " is a noop.")) { |
| 79 |
if (!(name %in% names(ShinySession$public_methods))) |
| 80 |
stop(name, " is not public method of ShinySession.") |
| 81 |
impl <- ShinySession$public_methods[[name]] |
| 82 |
body(impl) <- rlang::expr({ |
| 83 |
# Force arguments |
| 84 |
!!lapply(formalArgs(impl), rlang::sym) |
| 85 |
# Evade "no visible binding" note for reference to `private` |
| 86 |
(!!as.symbol("private"))$noopWarn(!!name, !!msg) |
| 87 |
invisible() |
| 88 |
}) |
| 89 |
impl |
| 90 |
} |
| 91 |
|
| 92 |
#' Accepts a series of symbols as arguments and generates corresponding noop |
| 93 |
#' implementations. |
| 94 |
#' @noRd |
| 95 |
makeWarnNoops <- function(...) { |
| 96 |
methods <- as.character(list(...)) |
| 97 |
names(methods) <- methods |
| 98 |
lapply(methods, makeNoop) |
| 99 |
} |
| 100 |
|
| 101 |
#' Returns an implementation of a ShinySession public method that signals an |
| 102 |
#' error. |
| 103 |
#' @include shiny.R |
| 104 |
#' @noRd |
| 105 |
makeError <- function(name, msg = paste0(name, " is for internal use only.")) { |
| 106 |
if (!(name %in% names(ShinySession$public_methods))) |
| 107 |
stop(name, " is not public method of ShinySession.") |
| 108 |
impl <- ShinySession$public_methods[[name]] |
| 109 |
body(impl) <- rlang::expr({ |
| 110 |
base::stop(!!msg) |
| 111 |
}) |
| 112 |
impl |
| 113 |
} |
| 114 |
|
| 115 |
#' Accepts a series of named arguments. Each name corresponds to a ShinySession |
| 116 |
#' public method that should signal an error, and each argument corresponds to |
| 117 |
#' an error message. |
| 118 |
#' @noRd |
| 119 |
makeErrors <- function(...) { |
| 120 |
errors <- rlang::list2(...) |
| 121 |
mapply(makeError, names(errors), errors, USE.NAMES = TRUE, SIMPLIFY = FALSE) |
| 122 |
} |
| 123 |
|
| 124 |
#' @noRd |
| 125 |
makeExtraMethods <- function() { |
| 126 |
c(makeWarnNoops( |
| 127 |
"allowReconnect", |
| 128 |
"decrementBusyCount", |
| 129 |
"doBookmark", |
| 130 |
"exportTestValues", |
| 131 |
"flushOutput", |
| 132 |
"getBookmarkExclude", |
| 133 |
"getTestSnapshotUrl", |
| 134 |
"incrementBusyCount", |
| 135 |
"manageHiddenOutputs", |
| 136 |
"manageInputs", |
| 137 |
"onBookmark", |
| 138 |
"onBookmarked", |
| 139 |
"onInputReceived", |
| 140 |
"onRestore", |
| 141 |
"onRestored", |
| 142 |
"outputOptions", |
| 143 |
"reactlog", |
| 144 |
# TODO Consider implementing this. Would require a new method like |
| 145 |
# session$getDataObj() to access in a test expression. |
| 146 |
"registerDataObj", |
| 147 |
"reload", |
| 148 |
"resetBrush", |
| 149 |
"sendBinaryMessage", |
| 150 |
"sendChangeTabVisibility", |
| 151 |
"sendCustomMessage", |
| 152 |
"sendInputMessage", |
| 153 |
"sendInsertTab", |
| 154 |
"sendInsertUI", |
| 155 |
"sendModal", |
| 156 |
"setCurrentTheme", |
| 157 |
"getCurrentTheme", |
| 158 |
"sendNotification", |
| 159 |
"sendProgress", |
| 160 |
"sendRemoveTab", |
| 161 |
"sendRemoveUI", |
| 162 |
"setBookmarkExclude", |
| 163 |
"setShowcase", |
| 164 |
"showProgress", |
| 165 |
"updateQueryString" |
| 166 |
), makeErrors( |
| 167 |
`@uploadEnd` = "for internal use only", |
| 168 |
`@uploadInit` = "for internal use only", |
| 169 |
createBookmarkObservers = "for internal use only", |
| 170 |
dispatch = "for internal use only", |
| 171 |
handleRequest = "for internal use only", |
| 172 |
requestFlush = "for internal use only", |
| 173 |
startTiming = "for internal use only", |
| 174 |
wsClosed = "for internal use only" |
| 175 |
)) |
| 176 |
} |
| 177 |
|
| 178 |
#' @description Adds generated instance methods to a MockShinySession instance. |
| 179 |
#' Note that `lock_objects = FALSE` must be set in the call to `R6Class()` |
| 180 |
#' that produced the generator object of the instance. |
| 181 |
#' @param instance instance of an R6 object, generally a `MockShinySession`. |
| 182 |
#' @param methods named list of method names to method implementation functions. |
| 183 |
#' In our typical usage, each function is derived from a public method of |
| 184 |
#' `ShinySession`. The environment of each implementation function is set to |
| 185 |
#' `instance$.__enclos_env` before the method is added. |
| 186 |
#' @noRd |
| 187 |
addGeneratedInstanceMethods <- function(instance, methods = makeExtraMethods()) { |
| 188 |
mapply(function(name, impl) { |
| 189 |
environment(impl) <- instance$.__enclos_env__ |
| 190 |
instance[[name]] <- impl |
| 191 |
}, names(methods), methods) |
| 192 |
} |
| 193 |
|
| 194 |
#' Mock Shiny Session |
| 195 |
#' |
| 196 |
#' @description An R6 class suitable for testing purposes. Simulates, to the |
| 197 |
#' extent possible, the behavior of the `ShinySession` class. The `session` |
| 198 |
#' parameter provided to Shiny server functions and modules is an instance of |
| 199 |
#' a `ShinySession` in normal operation. |
| 200 |
#' |
| 201 |
#' Most kinds of module and server testing do not require this class be |
| 202 |
#' instantiated manually. See instead [testServer()]. |
| 203 |
#' |
| 204 |
#' In order to support advanced usage, instances of `MockShinySession` are |
| 205 |
#' **unlocked** so that public methods and fields of instances may be |
| 206 |
#' modified. For example, in order to test authentication workflows, the |
| 207 |
#' `user` or `groups` fields may be overridden. Modified instances of |
| 208 |
#' `MockShinySession` may then be passed explicitly as the `session` argument |
| 209 |
#' of [testServer()]. |
| 210 |
#' |
| 211 |
#' @include timer.R |
| 212 |
#' @export |
| 213 |
MockShinySession <- R6Class( |
| 214 |
'MockShinySession', |
| 215 |
portable = FALSE, |
| 216 |
lock_objects = FALSE, |
| 217 |
public = list( |
| 218 |
#' @field env The environment associated with the session. |
| 219 |
env = NULL, |
| 220 |
#' @field returned The value returned by the module under test. |
| 221 |
returned = NULL, |
| 222 |
#' @field singletons Hardcoded as empty. Needed for rendering HTML (i.e. renderUI). |
| 223 |
singletons = character(0), |
| 224 |
#' @field clientData Mock client data that always returns a size for plots. |
| 225 |
clientData = structure(list(), class="mockclientdata"), |
| 226 |
#' @field output The shinyoutputs associated with the session. |
| 227 |
output = NULL, |
| 228 |
#' @field input The reactive inputs associated with the session. |
| 229 |
input = NULL, |
| 230 |
#' @field userData An environment initialized as empty. |
| 231 |
userData = NULL, |
| 232 |
#' @field progressStack A stack of progress objects. |
| 233 |
progressStack = 'Stack', |
| 234 |
#' @field token On a real `ShinySession`, used to identify this instance in URLs. |
| 235 |
token = 'character', |
| 236 |
#' @field cache The session cache object. |
| 237 |
cache = NULL, |
| 238 |
#' @field appcache The app cache object. |
| 239 |
appcache = NULL, |
| 240 |
#' @field restoreContext Part of bookmarking support in a real |
| 241 |
#' `ShinySession` but always `NULL` for a `MockShinySession`. |
| 242 |
restoreContext = NULL, |
| 243 |
#' @field groups Character vector of groups associated with an authenticated |
| 244 |
#' user. Always `NULL` for a `MockShinySesion`. |
| 245 |
groups = NULL, |
| 246 |
#' @field user The username of an authenticated user. Always `NULL` for a |
| 247 |
#' `MockShinySession`. |
| 248 |
user = NULL, |
| 249 |
#' @field options A list containing session-level shinyOptions. |
| 250 |
options = NULL, |
| 251 |
|
| 252 |
#' @description Create a new MockShinySession. |
| 253 |
initialize = function() { |
| 254 |
private$.input <- ReactiveValues$new(dedupe = FALSE, label = "input") |
| 255 |
private$flushCBs <- Callbacks$new() |
| 256 |
private$flushedCBs <- Callbacks$new() |
| 257 |
private$endedCBs <- Callbacks$new() |
| 258 |
|
| 259 |
private$file_generators <- fastmap() |
| 260 |
|
| 261 |
private$timer <- MockableTimerCallbacks$new() |
| 262 |
self$progressStack <- fastmap::faststack() |
| 263 |
|
| 264 |
self$userData <- new.env(parent=emptyenv()) |
| 265 |
|
| 266 |
# create output |
| 267 |
out <- .createOutputWriter(self) |
| 268 |
class(out) <- "shinyoutput" |
| 269 |
self$output <- out |
| 270 |
|
| 271 |
# Create a read-only copy of the inputs reactive. |
| 272 |
self$input <- .createReactiveValues(private$.input, readonly = TRUE) |
| 273 |
|
| 274 |
self$token <- createUniqueId(16) |
| 275 |
|
| 276 |
# Copy app-level options |
| 277 |
self$options <- getCurrentAppState()$options |
| 278 |
|
| 279 |
self$cache <- cachem::cache_mem() |
| 280 |
self$appcache <- cachem::cache_mem() |
| 281 |
|
| 282 |
# Adds various generated noop and error-producing method implementations. |
| 283 |
# Note that noop methods can be configured to produce warnings by setting |
| 284 |
# the option shiny.mocksession.warn = TRUE; see $noopWarn() for details. |
| 285 |
addGeneratedInstanceMethods(self) |
| 286 |
}, |
| 287 |
#' @description Define a callback to be invoked before a reactive flush |
| 288 |
#' @param fun The function to invoke |
| 289 |
#' @param once If `TRUE`, will only run once. Otherwise, will run every time reactives are flushed. |
| 290 |
onFlush = function(fun, once=TRUE) { |
| 291 |
if (!isTRUE(once)) { |
| 292 |
return(private$flushCBs$register(fun)) |
| 293 |
} else { |
| 294 |
dereg <- private$flushCBs$register(function() { |
| 295 |
dereg() |
| 296 |
fun() |
| 297 |
}) |
| 298 |
return(dereg) |
| 299 |
} |
| 300 |
}, |
| 301 |
#' @description Define a callback to be invoked after a reactive flush |
| 302 |
#' @param fun The function to invoke |
| 303 |
#' @param once If `TRUE`, will only run once. Otherwise, will run every time reactives are flushed. |
| 304 |
onFlushed = function(fun, once=TRUE) { |
| 305 |
if (!isTRUE(once)) { |
| 306 |
return(private$flushedCBs$register(fun)) |
| 307 |
} else { |
| 308 |
dereg <- private$flushedCBs$register(function() { |
| 309 |
dereg() |
| 310 |
fun() |
| 311 |
}) |
| 312 |
return(dereg) |
| 313 |
} |
| 314 |
}, |
| 315 |
#' @description Define a callback to be invoked when the session ends |
| 316 |
#' @param sessionEndedCallback The callback to invoke when the session has ended. |
| 317 |
onEnded = function(sessionEndedCallback) { |
| 318 |
private$endedCBs$register(sessionEndedCallback) |
| 319 |
}, |
| 320 |
|
| 321 |
#' @description Returns `FALSE` if the session has not yet been closed |
| 322 |
isEnded = function(){ private$was_closed }, |
| 323 |
#' @description Returns `FALSE` if the session has not yet been closed |
| 324 |
isClosed = function(){ private$was_closed }, |
| 325 |
#' @description Closes the session |
| 326 |
close = function(){ |
| 327 |
for (output in private$output) { |
| 328 |
output$suspend() |
| 329 |
} |
| 330 |
withReactiveDomain(self, { |
| 331 |
private$endedCBs$invoke(onError = printError, ..stacktraceon = TRUE) |
| 332 |
}) |
| 333 |
private$was_closed <- TRUE |
| 334 |
}, |
| 335 |
|
| 336 |
#FIXME: this is wrong. Will need to be more complex. |
| 337 |
#' @description Unsophisticated mock implementation that merely invokes |
| 338 |
# the given callback immediately. |
| 339 |
#' @param callback The callback to be invoked. |
| 340 |
cycleStartAction = function(callback){ callback() }, |
| 341 |
|
| 342 |
#' @description Base64-encode the given file. Needed for image rendering. |
| 343 |
#' @param name Not used |
| 344 |
#' @param file The file to be encoded |
| 345 |
#' @param contentType The content type of the base64-encoded string |
| 346 |
fileUrl = function(name, file, contentType='application/octet-stream') { |
| 347 |
bytes <- file.info(file)$size |
| 348 |
if (is.na(bytes)) |
| 349 |
return(NULL) |
| 350 |
|
| 351 |
fileData <- readBin(file, 'raw', n=bytes) |
| 352 |
b64 <- rawToBase64(fileData) |
| 353 |
return(paste('data:', contentType, ';base64,', b64, sep='')) |
| 354 |
}, |
| 355 |
|
| 356 |
#' @description Sets reactive values associated with the `session$inputs` |
| 357 |
#' object and flushes the reactives. |
| 358 |
#' @param ... The inputs to set. These arguments are processed with |
| 359 |
#' [rlang::list2()] and so are _[dynamic][rlang::dyn-dots]_. Input names |
| 360 |
#' may not be duplicated. |
| 361 |
#' @examples |
| 362 |
#' \dontrun{ |
| 363 |
#' session$setInputs(x=1, y=2) |
| 364 |
#' } |
| 365 |
setInputs = function(...) { |
| 366 |
vals <- rlang::dots_list(..., .homonyms = "error") |
| 367 |
mapply(names(vals), vals, FUN = function(name, value) { |
| 368 |
private$.input$set(name, value) |
| 369 |
}) |
| 370 |
private$flush() |
| 371 |
}, |
| 372 |
|
| 373 |
#' @description An internal method which shouldn't be used by others. |
| 374 |
#' Schedules `callback` for execution after some number of `millis` |
| 375 |
#' milliseconds. |
| 376 |
#' @param millis The number of milliseconds on which to schedule a callback |
| 377 |
#' @param callback The function to schedule. |
| 378 |
.scheduleTask = function(millis, callback) { |
| 379 |
id <- private$timer$schedule(millis, callback) |
| 380 |
|
| 381 |
# Return a deregistration callback |
| 382 |
function() { |
| 383 |
invisible(private$timer$unschedule(id)) |
| 384 |
} |
| 385 |
}, |
| 386 |
|
| 387 |
#' @description Simulate the passing of time by the given number of milliseconds. |
| 388 |
#' @param millis The number of milliseconds to advance time. |
| 389 |
elapse = function(millis) { |
| 390 |
msLeft <- millis |
| 391 |
|
| 392 |
while (msLeft > 0){ |
| 393 |
t <- private$timer$timeToNextEvent() |
| 394 |
|
| 395 |
if (is.infinite(t) || t <= 0 || msLeft < t){ |
| 396 |
# Either there's no good upcoming event or we can't make it to it in the allotted time. |
| 397 |
break |
| 398 |
} |
| 399 |
msLeft <- msLeft - t |
| 400 |
private$timer$elapse(t) |
| 401 |
|
| 402 |
# timerCallbacks must run before flushReact. |
| 403 |
private$timer$executeElapsed() |
| 404 |
private$flush() |
| 405 |
} |
| 406 |
|
| 407 |
private$timer$elapse(msLeft) |
| 408 |
|
| 409 |
# Run again in case our callbacks resulted in a scheduled |
| 410 |
# function that needs executing. |
| 411 |
private$timer$executeElapsed() |
| 412 |
private$flush() |
| 413 |
}, |
| 414 |
|
| 415 |
#' @description An internal method which shouldn't be used by others. |
| 416 |
#' @return Elapsed time in milliseconds. |
| 417 |
.now = function() { |
| 418 |
private$timer$getElapsed() |
| 419 |
}, |
| 420 |
|
| 421 |
#' @description An internal method which shouldn't be used by others. |
| 422 |
#' Defines an output in a way that sets private$currentOutputName |
| 423 |
#' appropriately. |
| 424 |
#' @param name The name of the output. |
| 425 |
#' @param func The render definition. |
| 426 |
#' @param label Not used. |
| 427 |
defineOutput = function(name, func, label) { |
| 428 |
force(name) |
| 429 |
|
| 430 |
if (!is.null(private$outs[[name]]$obs)) { |
| 431 |
private$outs[[name]]$obs$destroy() |
| 432 |
} |
| 433 |
|
| 434 |
if (is.null(func)) func <- missingOutput |
| 435 |
|
| 436 |
if (!is.function(func)) |
| 437 |
stop(paste("Unexpected", class(func), "output for", name)) |
| 438 |
|
| 439 |
with_no_otel_collect({ |
| 440 |
obs <- observe({ |
| 441 |
# We could just stash the promise, but we get an "unhandled promise error". This bypasses |
| 442 |
prom <- NULL |
| 443 |
tryCatch({ |
| 444 |
v <- private$withCurrentOutput(name, func(self, name)) |
| 445 |
if (!is.promise(v)){ |
| 446 |
# Make our sync value into a promise |
| 447 |
prom <- promise_resolve(v) |
| 448 |
} else { |
| 449 |
prom <- v |
| 450 |
} |
| 451 |
}, error=function(e){ |
| 452 |
# Error running value() |
| 453 |
prom <<- promise_reject(e) |
| 454 |
}) |
| 455 |
|
| 456 |
private$outs[[name]]$promise <- hybrid_chain( |
| 457 |
prom, |
| 458 |
function(v){ |
| 459 |
list(val = v, err = NULL) |
| 460 |
}, catch=function(e){ |
| 461 |
if ( |
| 462 |
!inherits(e, c("shiny.custom.error", "shiny.output.cancel", "shiny.output.progress", "shiny.silent.error")) |
| 463 |
) { |
| 464 |
self$unhandledError(e, close = FALSE) |
| 465 |
} |
| 466 |
list(val = NULL, err = e) |
| 467 |
}) |
| 468 |
}) |
| 469 |
}) |
| 470 |
private$outs[[name]] <- list(obs = obs, func = func, promise = NULL) |
| 471 |
}, |
| 472 |
|
| 473 |
#' @description An internal method which shouldn't be used by others. Forces |
| 474 |
#' evaluation of any reactive dependencies of the output function. |
| 475 |
#' @param name The name of the output. |
| 476 |
#' @return The return value of the function responsible for rendering the |
| 477 |
#' output. |
| 478 |
getOutput = function(name) { |
| 479 |
# Unlike the real outputs, we're going to return the last value rather than the unevaluated function |
| 480 |
if (is.null(private$outs[[name]])) { |
| 481 |
stop("The test referenced an output that hasn't been defined yet: output$", name) |
| 482 |
} |
| 483 |
|
| 484 |
if (is.null(private$outs[[name]]$promise)) { |
| 485 |
# Means the output was defined but the observer hasn't had a chance to run |
| 486 |
# yet. Run flushReact() now to force the observer to run. |
| 487 |
flushReact() |
| 488 |
|
| 489 |
if (is.null(private$outs[[name]]$promise)) { |
| 490 |
stop("output$", name, " encountered an unexpected error resolving its promise") |
| 491 |
} |
| 492 |
} |
| 493 |
|
| 494 |
# Make promise return |
| 495 |
v <- extract(private$outs[[name]]$promise) |
| 496 |
if (!is.null(v$err)){ |
| 497 |
stop(v$err) |
| 498 |
} else if (private$file_generators$has(self$ns(name))) { |
| 499 |
download <- private$file_generators$get(self$ns(name)) |
| 500 |
private$renderFile(self$ns(name), download) |
| 501 |
} else { |
| 502 |
v$val |
| 503 |
} |
| 504 |
}, |
| 505 |
|
| 506 |
#' @description Returns the given id prefixed by this namespace's id. |
| 507 |
#' @param id The id to prefix with a namespace id. |
| 508 |
#' @return The id with a namespace prefix. |
| 509 |
ns = function(id) { |
| 510 |
NS(private$nsPrefix, id) |
| 511 |
}, |
| 512 |
#' @description Trigger a reactive flush right now. |
| 513 |
flushReact = function(){ |
| 514 |
private$flush() |
| 515 |
}, |
| 516 |
#' @description Create and return a namespace-specific session proxy. |
| 517 |
#' @param namespace Character vector indicating a namespace. |
| 518 |
#' @return A new session proxy. |
| 519 |
makeScope = function(namespace) { |
| 520 |
ns <- NS(namespace) |
| 521 |
createSessionProxy( |
| 522 |
self, |
| 523 |
input = .createReactiveValues(private$.input, readonly = TRUE, ns = ns), |
| 524 |
output = structure(.createOutputWriter(self, ns = ns), class = "shinyoutput"), |
| 525 |
makeScope = function(namespace) self$makeScope(ns(namespace)), |
| 526 |
ns = function(namespace) ns(namespace), |
| 527 |
setInputs = function(...) { |
| 528 |
self$setInputs(!!!mapNames(ns, rlang::dots_list(..., .homonyms = "error"))) |
| 529 |
} |
| 530 |
) |
| 531 |
}, |
| 532 |
#' @description Set the environment associated with a testServer() call, but |
| 533 |
#' only if it has not previously been set. This ensures that only the |
| 534 |
#' environment of the outermost module under test is the one retained. In |
| 535 |
#' other words, the first assignment wins. |
| 536 |
#' @param env The environment to retain. |
| 537 |
#' @return The provided `env`. |
| 538 |
setEnv = function(env) { |
| 539 |
if (is.null(self$env)) { |
| 540 |
stopifnot(all(c("input", "output", "session") %in% ls(env))) |
| 541 |
self$env <- env |
| 542 |
} |
| 543 |
}, |
| 544 |
#' @description Set the value returned by the module call and proactively |
| 545 |
#' flush. Note that this method may be called multiple times if modules |
| 546 |
#' are nested. The last assignment, corresponding to an invocation of |
| 547 |
#' setReturned() in the outermost module, wins. |
| 548 |
#' @param value The value returned from the module |
| 549 |
#' @return The provided `value`. |
| 550 |
setReturned = function(value) { |
| 551 |
self$returned <- value |
| 552 |
value |
| 553 |
}, |
| 554 |
#' @description Get the value returned by the module call. |
| 555 |
#' @return The value returned by the module call |
| 556 |
getReturned = function() self$returned, |
| 557 |
#' @description Generate a distinct character identifier for use as a proxy |
| 558 |
#' namespace. |
| 559 |
#' @return A character identifier unique to the current session. |
| 560 |
genId = function() { |
| 561 |
private$idCounter <- private$idCounter + 1 |
| 562 |
paste0("proxy", private$idCounter) |
| 563 |
}, |
| 564 |
#' @description Provides a way to access the root `MockShinySession` from |
| 565 |
#' any descendant proxy. |
| 566 |
#' @return The root `MockShinySession`. |
| 567 |
rootScope = function() { |
| 568 |
self |
| 569 |
}, |
| 570 |
#' @description Add an unhandled error callback. |
| 571 |
#' @param callback The callback to add, which should accept an error object |
| 572 |
#' as its first argument. |
| 573 |
#' @return A deregistration function. |
| 574 |
onUnhandledError = function(callback) { |
| 575 |
private$unhandledErrorCallbacks$register(callback) |
| 576 |
}, |
| 577 |
#' @description Called by observers when a reactive expression errors. |
| 578 |
#' @param e An error object. |
| 579 |
#' @param close If `TRUE`, the session will be closed after the error is |
| 580 |
#' handled, defaults to `FALSE`. |
| 581 |
unhandledError = function(e, close = TRUE) { |
| 582 |
if (close) { |
| 583 |
class(e) <- c("shiny.error.fatal", class(e)) |
| 584 |
} |
| 585 |
|
| 586 |
private$unhandledErrorCallbacks$invoke(e, onError = printError) |
| 587 |
.globals$onUnhandledErrorCallbacks$invoke(e, onError = printError) |
| 588 |
|
| 589 |
if (close) self$close() |
| 590 |
}, |
| 591 |
#' @description Freeze a value until the flush cycle completes. |
| 592 |
#' @param x A `ReactiveValues` object. |
| 593 |
#' @param name The name of a reactive value within `x`. |
| 594 |
freezeValue = function(x, name) { |
| 595 |
if (!is.reactivevalues(x)) |
| 596 |
stop("x must be a reactivevalues object") |
| 597 |
|
| 598 |
impl <- .subset2(x, 'impl') |
| 599 |
key <- .subset2(x, 'ns')(name) |
| 600 |
impl$freeze(key) |
| 601 |
self$onFlushed(function() impl$thaw(key)) |
| 602 |
}, |
| 603 |
#' @description Registers the given callback to be invoked when the session |
| 604 |
#' is closed (i.e. the connection to the client has been severed). The |
| 605 |
#' return value is a function which unregisters the callback. If multiple |
| 606 |
#' callbacks are registered, the order in which they are invoked is not |
| 607 |
#' guaranteed. |
| 608 |
#' @param sessionEndedCallback Function to call when the session ends. |
| 609 |
onSessionEnded = function(sessionEndedCallback) { |
| 610 |
self$onEnded(sessionEndedCallback) |
| 611 |
}, |
| 612 |
#' @description Associated a downloadable file with the session. |
| 613 |
#' @param name The un-namespaced output name to associate with the |
| 614 |
#' downloadable file. |
| 615 |
#' @param filename A string or function designating the name of the file. |
| 616 |
#' @param contentType A string of the content type of the file. Not used by |
| 617 |
#' `MockShinySession`. |
| 618 |
#' @param content A function that takes a single argument file that is a |
| 619 |
#' file path (string) of a nonexistent temp file, and writes the content |
| 620 |
#' to that file path. (Reactive values and functions may be used from this |
| 621 |
#' function.) |
| 622 |
registerDownload = function(name, filename, contentType, content) { |
| 623 |
private$file_generators$set(self$ns(name), list( |
| 624 |
filename = if (is.function(filename)) filename else function() filename, |
| 625 |
content = content |
| 626 |
)) |
| 627 |
}, |
| 628 |
#' @description Get information about the output that is currently being |
| 629 |
#' executed. |
| 630 |
#' @return A list with with the `name` of the output. If no output is |
| 631 |
#' currently being executed, this will return `NULL`. |
| 632 |
getCurrentOutputInfo = function() { |
| 633 |
name <- private$currentOutputName |
| 634 |
if (is.null(name)) NULL else list(name = name) |
| 635 |
} |
| 636 |
), |
| 637 |
private = list( |
| 638 |
# @field .input Internal ReactiveValues object for normal input sent from client. |
| 639 |
.input = NULL, |
| 640 |
# @field flushCBs `Callbacks` called before flush. |
| 641 |
flushCBs = NULL, |
| 642 |
# @field flushedCBs `Callbacks` called after flush. |
| 643 |
flushedCBs = NULL, |
| 644 |
# @field endedCBs `Callbacks` called when session ends. |
| 645 |
endedCBs = NULL, |
| 646 |
# @field unhandledErrorCallbacks `Callbacks` called when an unhandled error |
| 647 |
# occurs. |
| 648 |
unhandledErrorCallbacks = Callbacks$new(), |
| 649 |
# @field timer `MockableTimerCallbacks` called at particular times. |
| 650 |
timer = NULL, |
| 651 |
# @field was_closed Set to `TRUE` once the session is closed. |
| 652 |
was_closed = FALSE, |
| 653 |
# @field outs List of namespaced output names. |
| 654 |
outs = list(), |
| 655 |
# @field nsPrefix Prefix with which to namespace inputs and outputs. |
| 656 |
nsPrefix = "mock-session", |
| 657 |
# @field idCounter Incremented every time `$genId()` is called. |
| 658 |
idCounter = 0, |
| 659 |
# @field file_generators Map of namespaced output names to lists with |
| 660 |
# `filename` and `output` elements, each a function. Updated by |
| 661 |
# `$registerDownload()` and read by `$getOutput()`. Files are generated |
| 662 |
# on demand when the output is accessed. |
| 663 |
file_generators = NULL, |
| 664 |
# @field currentOutputName Namespaced name of the currently executing |
| 665 |
#' output, or `NULL` if no output is currently executing. |
| 666 |
currentOutputName = NULL, |
| 667 |
|
| 668 |
# @description Writes a downloadable file to disk. If the `content` function |
| 669 |
# associated with a download handler does not write a file, an error is |
| 670 |
# signaled. Created files are deleted upon session close. |
| 671 |
# @param name The eamespaced output name associated with the downloadable |
| 672 |
# file. |
| 673 |
# @param download List with two names, `filename` and `content`. Both should |
| 674 |
# be functions. `filename` should take no arguments and return a string. |
| 675 |
# `content` should accept a path argument and create a file at that path. |
| 676 |
# @return A path to a temp file. |
| 677 |
renderFile = function(name, download) { |
| 678 |
# We make our own tempdir here because it's not safe to delete the result |
| 679 |
# of tempdir(). |
| 680 |
tmpd <- tempfile() |
| 681 |
dir.create(tmpd, recursive = TRUE) |
| 682 |
self$onSessionEnded(function() unlink(tmpd, recursive = TRUE)) |
| 683 |
file <- file.path(tmpd, download$filename()) |
| 684 |
download$content(file) |
| 685 |
if (!file.exists(file)) |
| 686 |
error("downloadHandler for ", name, " did not write a file.") |
| 687 |
file |
| 688 |
}, |
| 689 |
|
| 690 |
# @description Calls `shiny:::flushReact()` and executes all callbacks |
| 691 |
# related to reactivity. |
| 692 |
flush = function(){ |
| 693 |
isolate(private$flushCBs$invoke(..stacktraceon = TRUE)) |
| 694 |
shiny:::flushReact() # namespace to avoid calling our own method |
| 695 |
isolate(private$flushedCBs$invoke(..stacktraceon = TRUE)) |
| 696 |
later::run_now() |
| 697 |
}, |
| 698 |
|
| 699 |
# @description Produces a warning if the option `shiny.mocksession.warn` is |
| 700 |
# unset and not `FALSE`. |
| 701 |
# @param name The name of the mocked method. |
| 702 |
# @param msg A message describing why the method is not implemented. |
| 703 |
noopWarn = function(name, msg) { |
| 704 |
if (getOption("shiny.mocksession.warn", FALSE) == FALSE) |
| 705 |
return(invisible()) |
| 706 |
out <- paste0(name, " is not fully implemented by MockShinySession: ", msg) |
| 707 |
out <- paste0(out, "\n", "To disable messages like this, run `options(shiny.mocksession.warn=FALSE)`") |
| 708 |
warning(out, call. = FALSE) |
| 709 |
}, |
| 710 |
|
| 711 |
# @description Binds a domain to `expr` and uses `createVarPromiseDomain()` |
| 712 |
# to ensure `private$currentOutputName` is set to `name` around any of |
| 713 |
# the promise's callbacks. Domains are something like dynamic scopes but |
| 714 |
# for promise chains instead of the call stack. |
| 715 |
# @return A promise. |
| 716 |
withCurrentOutput = function(name, expr) { |
| 717 |
if (!is.null(private$currentOutputName)) { |
| 718 |
stop("Nested calls to withCurrentOutput() are not allowed.") |
| 719 |
} |
| 720 |
|
| 721 |
with_promise_domain( |
| 722 |
createVarPromiseDomain(private, "currentOutputName", name), |
| 723 |
expr |
| 724 |
) |
| 725 |
} |
| 726 |
), |
| 727 |
active = list( |
| 728 |
#' @field files For internal use only. |
| 729 |
files = function() stop("$files is for internal use only."), |
| 730 |
#' @field downloads For internal use only. |
| 731 |
downloads = function() stop("$downloads is for internal use only."), |
| 732 |
#' @field closed Deprecated in `ShinySession` and signals an error. |
| 733 |
closed = function() stop("$closed is deprecated"), |
| 734 |
#' @field session Deprecated in ShinySession and signals an error. |
| 735 |
session = function() stop("$session is deprecated"), |
| 736 |
#' @field request An empty environment where the request should be. The request isn't meaningfully mocked currently. |
| 737 |
request = function(value) { |
| 738 |
if (!missing(value)){ |
| 739 |
stop("session$request can't be assigned to") |
| 740 |
} |
| 741 |
warning("session$request doesn't currently simulate a realistic request on MockShinySession") |
| 742 |
new.env(parent=emptyenv()) |
| 743 |
} |
| 744 |
) |
| 745 |
) |