tests/testthat/test-validate.R

test_that("validate_runtime_strategy accepts valid strategies", {
  expect_silent(validate_runtime_strategy("shinylive"))
  expect_silent(validate_runtime_strategy("bundled"))
  expect_silent(validate_runtime_strategy("system"))
  expect_silent(validate_runtime_strategy("auto-download"))
  expect_silent(validate_runtime_strategy("container"))
})

test_that("validate_runtime_strategy rejects invalid strategies", {
  expect_error(validate_runtime_strategy("invalid"), "Invalid runtime strategy")
  expect_error(validate_runtime_strategy("docker"), "Invalid runtime strategy")
})

test_that("validate_python_app_structure checks for app.py", {
  tmpdir <- tempfile()
  dir.create(tmpdir)
  on.exit(unlink(tmpdir, recursive = TRUE), add = TRUE)

  expect_error(validate_python_app_structure(tmpdir), "app.py")

  writeLines("from shiny import App", file.path(tmpdir, "app.py"))
  expect_silent(validate_python_app_structure(tmpdir))
})

test_that("validate_r_available succeeds when Rscript is found", {
  # R CMD check's R_check_bin/Rscript shim does not always round-trip cleanly
  # through processx, causing this test to fail in the sandbox even though
  # Rscript is obviously present. Skip on CRAN and in R CMD check.
  skip_on_cran()
  skip_if(nzchar(Sys.getenv("_R_CHECK_PACKAGE_NAME_", "")))
  expect_silent(validate_r_available())
})

test_that("validate_r_available returns the Rscript path invisibly", {
  skip_on_cran()
  skip_if(nzchar(Sys.getenv("_R_CHECK_PACKAGE_NAME_", "")))
  result <- validate_r_available()
  expect_true(nzchar(result))
})

# Isolated tests that exercise the resolution logic without depending on the
# live Rscript shim, so they run in the standard CRAN / R CMD check pipeline.
test_that("validate_r_available errors when Rscript is not on PATH", {
  mockery::stub(validate_r_available, "Sys.getenv", function(...) "")
  mockery::stub(validate_r_available, "Sys.which", function(...) "")
  expect_error(validate_r_available(), "Rscript is required")
})

test_that("validate_r_available returns the resolved Rscript path", {
  mockery::stub(validate_r_available, "Sys.getenv", function(...) "checkmode")
  mockery::stub(validate_r_available, "Sys.which", function(...) "/usr/local/bin/Rscript")
  expect_equal(validate_r_available(), "/usr/local/bin/Rscript")
})

fake_command_output <- function(stdout) {
  list(status = 0L, stdout = paste0(stdout, "\n"), stderr = "")
}

test_that("validate_node_npm stops on a Node.js older than the minimum", {
  mockery::stub(validate_node_npm, "get_node_command", function(...) "node")
  mockery::stub(validate_node_npm, "get_npm_command", function(...) "npm")
  mockery::stub(validate_node_npm, "nodejs_is_installed", function() FALSE)
  # First call checks node, second checks npm
  mockery::stub(validate_node_npm, "run_command_safe",
                mockery::mock(fake_command_output("v22.11.0"), fake_command_output("11.5.0")))

  err <- expect_error(validate_node_npm(), class = "shinyelectron_node_too_old")
  msg <- cli::ansi_strip(conditionMessage(err))
  expect_match(msg, "22.11.0", fixed = TRUE)
  expect_match(msg, "22.12.0", fixed = TRUE)
  expect_match(msg, "install_nodejs()", fixed = TRUE)
})

test_that("validate_node_npm accepts Node.js at the minimum", {
  mockery::stub(validate_node_npm, "get_node_command", function(...) "node")
  mockery::stub(validate_node_npm, "get_npm_command", function(...) "npm")
  mockery::stub(validate_node_npm, "nodejs_is_installed", function() FALSE)
  mockery::stub(validate_node_npm, "run_command_safe",
                mockery::mock(fake_command_output("v22.12.0"), fake_command_output("11.5.0")))

  info <- validate_node_npm()
  expect_equal(info$node_version, "22.12.0")
  expect_equal(info$npm_version, "11.5.0")
})

test_that("assert_safe_to_overwrite refuses protected dirs", {
  expect_error(assert_safe_to_overwrite("/"), "protected")
  expect_error(assert_safe_to_overwrite(normalizePath("~", mustWork = FALSE)), "protected")
  expect_true(assert_safe_to_overwrite(withr::local_tempdir()))
})

# 4D-1: wizard platform validation
test_that("wizard aborts for an invalid platform token", {
  tmp <- withr::local_tempdir()
  # One reply per prompt, up to and including the platform prompt.
  responses <- c("", "", "1", "1", "badplatform")
  mockery::stub(wizard, "interactive", function() TRUE)
  mockery::stub(wizard, "readline", do.call(mockery::mock, as.list(responses)))
  expect_error(
    capture.output(suppressMessages(wizard(tmp)), type = "output"),
    "Invalid platform"
  )
})

# 4D-2: enable_auto_updates rejects unsupported providers with a clear message
test_that("enable_auto_updates rejects s3 provider with clear error", {
  tmp <- withr::local_tempdir()
  writeLines(
    "app:\n  name: test\nbuild:\n  type: r-shiny\n  runtime_strategy: shinylive\n",
    file.path(tmp, "_shinyelectron.yml")
  )
  expect_error(
    enable_auto_updates(tmp, provider = "s3", owner = "x", repo = "y"),
    "not yet supported"
  )
})

# 4D-3: scalar guards in validate_config
test_that("validate_config warns clearly for a length-2 window width", {
  cfg <- list(window = list(width = c(1200, 800)))
  expect_warning(validated <- validate_config(cfg), "window.width")
  expect_equal(validated$window$width, SHINYELECTRON_DEFAULTS$window_width)
})

test_that("validate_config warns clearly for a list window height", {
  cfg <- list(window = list(height = list(800, 600)))
  expect_warning(validated <- validate_config(cfg), "window.height")
  expect_equal(validated$window$height, SHINYELECTRON_DEFAULTS$window_height)
})

test_that("validate_config warns clearly for a length-2 server port", {
  cfg <- list(server = list(port = c(3838, 3839)))
  expect_warning(validated <- validate_config(cfg), "server.port")
  expect_equal(validated$server$port, SHINYELECTRON_DEFAULTS$server_port)
})

# --- validate_config: dependencies version-string checks ---

test_that("validate_config warns and drops non-character electron version", {
  cfg <- list(dependencies = list(electron = list(version = 123)))
  expect_warning(
    out <- validate_config(cfg),
    regexp = "dependencies.electron.version"
  )
  expect_null(out$dependencies$electron$version)
})

test_that("validate_config warns and drops non-character r version", {
  cfg <- list(dependencies = list(r = list(version = TRUE)))
  expect_warning(
    out <- validate_config(cfg),
    regexp = "dependencies.r.version"
  )
  expect_null(out$dependencies$r$version)
})

test_that("validate_config warns and drops length > 1 python version", {
  cfg <- list(dependencies = list(python = list(version = c("3.11.0", "3.12.0"))))
  expect_warning(
    out <- validate_config(cfg),
    regexp = "dependencies.python.version"
  )
  expect_null(out$dependencies$python$version)
})

test_that("validate_config accepts valid single-string version values", {
  cfg <- list(dependencies = list(
    r        = list(version = "4.5.1"),
    python   = list(version = "3.12.0"),
    electron = list(version = "latest")
  ))
  expect_no_warning(out <- validate_config(cfg))
  expect_equal(out$dependencies$r$version, "4.5.1")
  expect_equal(out$dependencies$python$version, "3.12.0")
  expect_equal(out$dependencies$electron$version, "latest")
})

# --- validate_config: dependencies system_packages checks ---

test_that("validate_config warns and drops list-shaped system_packages", {
  cfg <- list(dependencies = list(system_packages = list("a", "b")))
  expect_warning(
    out <- validate_config(cfg),
    regexp = "dependencies.system_packages"
  )
  expect_null(out$dependencies$system_packages)
})

test_that("validate_config accepts a character vector for system_packages", {
  cfg <- list(dependencies = list(system_packages = c("libfoo-dev", "libbar-dev")))
  expect_no_warning(out <- validate_config(cfg))
  expect_equal(out$dependencies$system_packages, c("libfoo-dev", "libbar-dev"))
})

# --- validate_config: Windows installer flags ---

test_that("validate_config accepts unset and logical installer flags", {
  expect_no_warning(out <- validate_config(default_config()))
  expect_equal(out$installer, default_config()$installer)

  cfg <- list(installer = list(
    one_click = FALSE,
    allow_to_change_installation_directory = TRUE,
    per_machine = TRUE
  ))
  expect_no_warning(out <- validate_config(cfg))
  expect_equal(out$installer, cfg$installer)
})

test_that("validate_config reads quoted installer flags with a warning", {
  cfg <- list(installer = list(one_click = "false"))
  expect_warning(out <- validate_config(cfg), class = "shinyelectron_quoted_flag")
  expect_identical(out$installer$one_click, FALSE)

  cfg <- list(installer = list(
    one_click = FALSE,
    allow_to_change_installation_directory = "true"
  ))
  expect_warning(out <- validate_config(cfg), "installer.allow_to_change_installation_directory",
                 class = "shinyelectron_quoted_flag")
  expect_identical(out$installer$allow_to_change_installation_directory, TRUE)

  cfg <- list(installer = list(per_machine = "Yes"))
  expect_warning(out <- validate_config(cfg), class = "shinyelectron_quoted_flag")
  expect_identical(out$installer$per_machine, TRUE)
})

test_that("validate_config rejects other non-logical installer flags", {
  keys <- c("one_click", "allow_to_change_installation_directory", "per_machine")
  bad_values <- list("maybe", "", 1L, NA, c(TRUE, FALSE))
  for (key in keys) {
    for (bad in bad_values) {
      cfg <- list(installer = list(one_click = FALSE))
      cfg$installer[key] <- list(bad)
      expect_error(validate_config(cfg), paste0("installer.", key), fixed = TRUE,
                   class = "shinyelectron_invalid_flag")
    }
  }
})

test_that("validate_config requires the wizard for a directory page", {
  cfg <- list(installer = list(
    one_click = TRUE,
    allow_to_change_installation_directory = TRUE
  ))
  expect_error(validate_config(cfg), "requires\\s+installer\\.one_click")

  # An unset one_click falls back to electron-builder's one-click default.
  cfg$installer$one_click <- NULL
  expect_error(validate_config(cfg), "requires\\s+installer\\.one_click")

  # Quoted values are read first, so the check still applies to them.
  quoted <- list(
    list(one_click = "true", allow_to_change_installation_directory = TRUE),
    list(one_click = TRUE, allow_to_change_installation_directory = "yes"),
    list(allow_to_change_installation_directory = "true")
  )
  for (installer in quoted) {
    expect_error(
      suppressWarnings(validate_config(list(installer = installer)),
                       classes = "shinyelectron_quoted_flag"),
      "requires\\s+installer\\.one_click"
    )
  }
})

test_that("read_config aborts on installer settings electron-builder would reject", {
  tmp <- withr::local_tempdir()
  config_path <- file.path(tmp, "_shinyelectron.yml")

  writeLines(c("installer:", "  allow_to_change_installation_directory: true"),
             config_path)
  expect_error(read_config(tmp), "requires\\s+installer\\.one_click")

  writeLines(c("installer:", "  one_click: maybe"), config_path)
  expect_error(read_config(tmp), "installer.one_click", fixed = TRUE,
               class = "shinyelectron_invalid_flag")

  writeLines(c("installer:", "  one_click: false",
               "  allow_to_change_installation_directory: true"),
             config_path)
  cfg <- read_config(tmp)
  expect_false(cfg$installer$one_click)
  expect_true(cfg$installer$allow_to_change_installation_directory)
})

test_that("a quoted one_click warns once and still builds a wizard", {
  tmp <- withr::local_tempdir()
  writeLines(c("installer:", "  one_click: \"false\""),
             file.path(tmp, "_shinyelectron.yml"))

  quoted_warning <- mockery::mock()
  cfg <- withCallingHandlers(
    read_config(tmp),
    shinyelectron_quoted_flag = function(w) {
      quoted_warning(conditionMessage(w))
      invokeRestart("muffleWarning")
    }
  )
  mockery::expect_called(quoted_warning, 1L)
  expect_identical(cfg$installer$one_click, FALSE)

  # The stored logical reaches package.json without a second warning.
  expect_no_warning(
    parsed <- jsonlite::fromJSON(
      generate_package_json("my-app", "1.0.0", "native-r", cfg),
      simplifyVector = FALSE
    )
  )
  expect_equal(parsed$build$nsis, list(oneClick = FALSE))
})

# --- validate_config: settings that take only true or false ---

# The settings config_flag() reads instead, with its own rules and classes.
flag_settings <- c(
  "installer.one_click", "installer.allow_to_change_installation_directory",
  "installer.per_machine", "dependencies.r.prune"
)

# A configuration that holds `value` at the dotted `path`.
config_with <- function(path, value) {
  keys <- strsplit(path, ".", fixed = TRUE)[[1]]
  Reduce(function(inner, key) stats::setNames(list(inner), key), rev(keys), value)
}

# The dotted paths of the single logical values in a nested list.
logical_leaves <- function(x, path = character(0)) {
  if (is.logical(x) && length(x) == 1L) return(paste(path, collapse = "."))
  if (!is_named_list(x)) return(character(0))
  leaves <- lapply(names(x), function(name) logical_leaves(x[[name]], c(path, name)))
  as.character(unlist(leaves))
}

# Write the init_config() template into `dir` with every commented-out
# setting switched on, and return the path of the file.
write_full_template <- function(dir) {
  init_config(dir, app_name = "Demo", overwrite = TRUE, verbose = FALSE)
  path <- file.path(dir, CONFIG_FILENAME)
  writeLines(
    sub('^(\\s*)# (\\s*)([a-z_]+:|"[^"]*":|- )', "\\1\\2\\3", readLines(path)),
    path
  )
  path
}

test_that("read_config stops on a quoted yes for updates.enabled", {
  tmp <- withr::local_tempdir()
  config_path <- file.path(tmp, "_shinyelectron.yml")

  writeLines(c("updates:", "  enabled: \"yes\""), config_path)
  err <- expect_error(read_config(tmp),
                      class = "shinyelectron_invalid_logical_setting")
  expect_match(conditionMessage(err), "updates.enabled", fixed = TRUE)
  expect_match(conditionMessage(err), "not the string \"yes\"", fixed = TRUE)
  expect_match(conditionMessage(err), "without quotes: `enabled: true`",
               fixed = TRUE)

  # Without the quotes YAML reads yes as true.
  writeLines(c("updates:", "  enabled: yes"), config_path)
  expect_true(read_config(tmp)$updates$enabled)
})

test_that("a quoted false no longer turns a setting on", {
  tmp <- withr::local_tempdir()
  writeLines(c("tray:", "  enabled: \"false\""),
             file.path(tmp, "_shinyelectron.yml"))
  err <- expect_error(read_config(tmp),
                      class = "shinyelectron_invalid_logical_setting")
  expect_match(conditionMessage(err), "tray.enabled", fixed = TRUE)
  expect_match(conditionMessage(err), "without quotes: `enabled: false`",
               fixed = TRUE)
})

test_that("validate_config stops on every kind of value that is not true or false", {
  held <- function(value) {
    err <- expect_error(
      validate_config(config_with("menu.enabled", value)),
      "menu.enabled", fixed = TRUE,
      class = "shinyelectron_invalid_logical_setting"
    )
    conditionMessage(err)
  }
  expect_match(held("maybe"), "not the string \"maybe\"", fixed = TRUE)
  expect_match(held(""), "not the string \"\"", fixed = TRUE)
  expect_match(held(1), "not the number 1", fixed = TRUE)
  expect_match(held(0L), "not the number 0", fixed = TRUE)
  expect_match(held(NA), "not `NA`", fixed = TRUE)
  expect_match(held(NA_character_), "not a character `NA`", fixed = TRUE)
  expect_match(held(c(TRUE, FALSE)), "not a logical vector", fixed = TRUE)
  expect_match(held(list(TRUE)), "not a list", fixed = TRUE)
  expect_match(held(list(value = TRUE)), "not a list", fixed = TRUE)

  # A quoted word for true or false, in any case, needs only its quotes
  # removed. Any other value gets both spellings.
  expect_match(held(" No "), "without quotes: `enabled: false`", fixed = TRUE)
  expect_match(held("On"), "without quotes: `enabled: true`", fixed = TRUE)
  expect_match(held("maybe"), "`enabled: true` or `enabled: false`", fixed = TRUE)
})

test_that("validate_config checks every setting that takes only true or false", {
  expect_contains(LOGICAL_SETTINGS, c("updates.enabled", "tray.enabled"))
  for (setting in LOGICAL_SETTINGS) {
    expect_error(validate_config(config_with(setting, "yes")),
                 setting, fixed = TRUE,
                 class = "shinyelectron_invalid_logical_setting")
    for (value in c(TRUE, FALSE)) {
      cfg <- config_with(setting, value)
      expect_no_warning(out <- validate_config(cfg))
      expect_identical(out, cfg, info = setting)
    }
  }
})

test_that("validate_config accepts a true/false setting that is absent", {
  expect_no_error(validate_config(list()))
  expect_no_error(validate_config(list(updates = list(provider = "github"))))
  expect_no_error(validate_config(list(updates = list(enabled = NULL))))
  # A section that is not a map holds no setting to check.
  expect_no_error(check_logical_settings(list(tray = "yes")))
})

test_that("every true/false setting in the defaults and the template is checked", {
  # A new true/false default belongs in LOGICAL_SETTINGS, unless config_flag()
  # reads it.
  expect_setequal(
    logical_leaves(default_config()),
    c(LOGICAL_SETTINGS, "installer.one_click", "dependencies.r.prune")
  )
  expect_length(intersect(LOGICAL_SETTINGS, flag_settings), 0)

  template <- yaml::read_yaml(write_full_template(withr::local_tempdir()))
  in_template <- logical_leaves(template)
  expect_contains(in_template, c("updates.enabled", "updates.github.private"))
  expect_in(in_template, c(LOGICAL_SETTINGS, flag_settings))
})

test_that("the init_config() template and the bundled example configurations validate", {
  dir <- withr::local_tempdir()
  init_config(dir, app_name = "Demo", verbose = FALSE)
  expect_no_error(read_config(dir))
  write_full_template(dir)
  expect_no_error(config <- read_config(dir))
  expect_false(config$updates$enabled)
  expect_true(config$container$pull_on_start)

  examples <- list.files(system.file("demos", package = "shinyelectron"),
                         pattern = "^_shinyelectron\\.yml$", recursive = TRUE,
                         full.names = TRUE)
  expect_gte(length(examples), 2)
  for (path in examples) {
    expect_no_error(read_config(dirname(path)))
  }
})

# --- Windows installer license ---

test_that("resolve_installer_license resolves the path against the app directory", {
  appdir <- withr::local_tempdir()
  writeLines("Terms of use", file.path(appdir, "LICENSE.txt"))

  cfg <- resolve_installer_license(
    list(installer = list(license_file = "LICENSE.txt")), appdir
  )
  expect_equal(cfg$installer$license_file,
               as.character(fs::path_abs(fs::path(appdir, "LICENSE.txt"))))

  # An absolute path is kept as is, and an unset license is left alone.
  again <- resolve_installer_license(cfg, withr::local_tempdir())
  expect_equal(again$installer$license_file, cfg$installer$license_file)
  expect_equal(resolve_installer_license(default_config(), appdir),
               default_config())
})

test_that("resolve_installer_license aborts on a missing or invalid license", {
  appdir <- withr::local_tempdir()
  resolve <- function(license_file) {
    resolve_installer_license(
      list(installer = list(license_file = license_file)), appdir
    )
  }
  expect_error(resolve("LICENSE.txt"), "License file not found")
  expect_error(resolve("."), "License file not found")
  expect_error(resolve(TRUE), "installer.license_file", fixed = TRUE)
  expect_error(resolve(""), "installer.license_file", fixed = TRUE)
})

test_that("export stops on a missing license file before building anything", {
  local_no_electron_lookup()
  appdir <- withr::local_tempdir()
  writeLines("library(shiny)", file.path(appdir, "app.R"))
  writeLines(c("installer:", "  license_file: LICENSE.txt"),
             file.path(appdir, "_shinyelectron.yml"))
  destdir <- file.path(withr::local_tempdir(), "out")

  expect_error(
    export(appdir, destdir, build = FALSE, verbose = FALSE),
    "License file not found"
  )
  expect_false(dir.exists(destdir))
})

# --- validate_icon ---

test_that("validate_icon accepts a PNG or .icns icon for every platform", {
  for (ext in c(".png", ".icns", ".PNG")) {
    icon <- withr::local_tempfile(fileext = ext)
    writeBin(as.raw(1:16), icon)
    expect_no_warning(validate_icon(icon, c("win", "mac", "linux")))
  }
})

test_that("validate_icon warns that an .ico icon serves Windows only", {
  icon <- withr::local_tempfile(fileext = ".ico")
  writeBin(as.raw(1:16), icon)
  expect_no_warning(validate_icon(icon, "win"))

  w <- expect_warning(
    validate_icon(icon, c("win", "mac", "linux")),
    class = "shinyelectron_icon_unsupported"
  )
  # cli wraps the message to the console width.
  msg <- gsub("[[:space:]]+", " ", cli::ansi_strip(conditionMessage(w)))
  expect_match(msg, "\"mac\" and \"linux\"", fixed = TRUE)
  expect_no_match(msg, "\"win\"", fixed = TRUE)
  expect_match(msg, "default Electron icon", fixed = TRUE)
})

test_that("validate_icon warns about a format no platform can use", {
  icon <- withr::local_tempfile(fileext = ".svg")
  writeBin(as.raw(1:16), icon)
  expect_warning(validate_icon(icon, "linux"),
                 class = "shinyelectron_icon_unsupported")
})

test_that("validate_icon warns about the platforms an image is too small for", {
  every <- c("win", "mac", "linux")
  expect_no_warning(validate_icon(local_png_icon(1024), every))
  expect_no_warning(validate_icon(local_png_icon(300), c("win", "linux")))

  w <- expect_warning(
    validate_icon(local_png_icon(300), every),
    class = "shinyelectron_icon_too_small"
  )
  expect_s3_class(w, "shinyelectron_icon_unsupported")
  # cli wraps the message to the console width.
  msg <- gsub("[[:space:]]+", " ", cli::ansi_strip(conditionMessage(w)))
  expect_match(msg, "too small for \"mac\".", fixed = TRUE)
  expect_match(msg, "at least 512x512 pixels for macOS.", fixed = TRUE)
  expect_match(msg, "The \"mac\" build will show the default Electron icon.",
               fixed = TRUE)

  # Windows needs an image of 256x256 or more in an .icns or .ico file.
  expect_no_warning(validate_icon(local_icns_icon("ic10"), every))
  w <- expect_warning(
    validate_icon(local_icns_icon("ic07"), every),
    class = "shinyelectron_icon_too_small"
  )
  msg <- gsub("[[:space:]]+", " ", cli::ansi_strip(conditionMessage(w)))
  expect_match(msg, "too small for \"win\".", fixed = TRUE)
  expect_match(msg, "at least 256x256 pixels for Windows.", fixed = TRUE)
  expect_warning(validate_icon(local_ico_icon(48), "win"),
                 class = "shinyelectron_icon_too_small")
})

test_that("validate_icon leaves out values that are not platforms", {
  local_no_electron_lookup()
  # app_check() passes on a platform argument that it reports as invalid.
  expect_no_warning(validate_icon(local_png_icon(1024), c("win", "macos")))
})

Try the shinyelectron package in your browser

Any scripts or data that you put into this service are public.

shinyelectron documentation built on Dec. 3, 2026, 9:07 a.m.