tests/testthat/test-package-sources.R

# Where an app's packages come from: Python requirement specs and sources,
# and whether R packages are on the configured repositories.

# A CRAN-like repository on disk whose source index lists `packages`, given
# as a file:// URL. `fields` adds lines to the named packages' entries.
local_cran_repo <- function(packages, fields = character(), env = parent.frame()) {
  dir <- withr::local_tempdir(.local_envir = env)
  contrib <- file.path(dir, "src", "contrib")
  dir.create(contrib, recursive = TRUE)
  entries <- vapply(packages, function(p) {
    paste(c(paste0("Package: ", p), "Version: 1.0.0", fields[names(fields) == p]),
          collapse = "\n")
  }, character(1))
  writeLines(paste(entries, collapse = "\n\n"), file.path(contrib, "PACKAGES"))
  path <- normalizePath(dir, winslash = "/")
  paste0("file://", if (startsWith(path, "/")) "" else "/", path)
}

# A library folder holding a DESCRIPTION for each of `descriptions`, a named
# list of extra DESCRIPTION lines.
local_fake_library <- function(descriptions, env = parent.frame()) {
  lib <- withr::local_tempdir(.local_envir = env)
  for (pkg in names(descriptions)) {
    dir.create(file.path(lib, pkg))
    writeLines(c(paste0("Package: ", pkg), "Version: 0.1.0", descriptions[[pkg]]),
               file.path(lib, pkg, "DESCRIPTION"))
  }
  lib
}

# An app directory with `file` holding `lines`.
local_py_app <- function(file, lines, env = parent.frame()) {
  dir <- withr::local_tempdir(.local_envir = env)
  writeLines("from shiny import App", file.path(dir, "app.py"))
  writeLines(lines, file.path(dir, file))
  dir
}

# --- Python requirement specs ---

test_that("requirements.txt pins and markers reach the install list", {
  app <- local_py_app("requirements.txt", c(
    "pandas==2.2.3",
    "numpy==2.4.6 ; python_full_version < '3.12'",
    "numpy==2.5.4 ; python_full_version >= '3.12'",
    "shiny>=1.8  # the app itself"
  ))

  reqs <- read_py_requirements(app)

  expect_equal(reqs$packages, c("numpy", "pandas", "shiny"))
  expect_equal(reqs$requirements, c(
    "pandas==2.2.3",
    "numpy==2.4.6 ; python_full_version < '3.12'",
    "numpy==2.5.4 ; python_full_version >= '3.12'",
    "shiny>=1.8"
  ))
})

test_that("hashed lines from uv export keep their pins and lose their hashes", {
  app <- local_py_app("requirements.txt", c(
    "# This file was autogenerated by uv via the following command:",
    "anyio==4.15.1 \\",
    "    --hash=sha256:aaa",
    "    # via starlette",
    "shiny==1.8.0 \\",
    "    --hash=sha256:bbb \\",
    "    --hash=sha256:ccc"
  ))

  reqs <- read_py_requirements(app)

  expect_equal(reqs$requirements, c("anyio==4.15.1", "shiny==1.8.0"))
  expect_equal(reqs$ignored, character(0))
})

test_that("requirements that point at a URL, VCS or path are set apart", {
  app <- local_py_app("requirements.txt", c(
    "great-tables @ git+https://github.com/posit-dev/great-tables@624100f",
    "git+https://github.com/me/other.git#egg=other",
    "-e ./local-pkg",
    "./wheels/inhouse-1.0-py3-none-any.whl",
    "https://example.com/pkg-1.0.tar.gz",
    "shiny"
  ))

  reqs <- read_py_requirements(app)

  expect_equal(reqs$direct, c(
    "great-tables @ git+https://github.com/posit-dev/great-tables@624100f",
    "git+https://github.com/me/other.git#egg=other",
    "-e ./local-pkg",
    "./wheels/inhouse-1.0-py3-none-any.whl",
    "https://example.com/pkg-1.0.tar.gz"
  ))
  expect_equal(reqs$requirements, "shiny")
  expect_equal(reqs$packages, c("great-tables", "shiny"))
})

test_that("pip option lines are listed as ignored", {
  app <- local_py_app("requirements.txt", c(
    "-r other.txt",
    "--extra-index-url https://example.com/simple",
    "-i https://mirror.example.com/simple",
    "pandas"
  ))

  reqs <- read_py_requirements(app)

  expect_equal(reqs$ignored, c(
    "-r other.txt",
    "--extra-index-url https://example.com/simple",
    "-i https://mirror.example.com/simple"
  ))
  expect_equal(reqs$requirements, "pandas")
})

test_that("pyproject.toml pins reach the install list", {
  app <- local_py_app("pyproject.toml", c(
    "[project]",
    "name = \"pyapp\"",
    "dependencies = [",
    "    \"pandas==2.2.3\",",
    "    \"shiny>=1.8.0\",",
    "]"
  ))

  reqs <- read_py_requirements(app)

  expect_equal(reqs$requirements, c("pandas==2.2.3", "shiny>=1.8.0"))
  expect_equal(reqs$packages, c("pandas", "shiny"))
})

test_that("a pyproject.toml direct reference is set apart", {
  app <- local_py_app("pyproject.toml", c(
    "[project]",
    "dependencies = [\"mylib @ https://example.com/mylib-1.0.tar.gz\", \"shiny\"]"
  ))

  reqs <- read_py_requirements(app)

  expect_equal(reqs$direct, "mylib @ https://example.com/mylib-1.0.tar.gz")
  expect_equal(reqs$requirements, "shiny")
})

test_that("uv sources that are not an index are set apart, matched by normalized name", {
  app <- local_py_app("pyproject.toml", c(
    "[project]",
    "dependencies = [\"Great_Tables\", \"mylib\", \"pandas==2.2.3\", \"shiny\"]",
    "",
    "[tool.uv.sources]",
    "great-tables = { git = \"https://github.com/posit-dev/great-tables\" }",
    "pytest = { git = \"https://github.com/pytest-dev/pytest\" }",
    "",
    "[tool.uv.sources.mylib]",
    "path = \"../mylib\""
  ))

  reqs <- read_py_requirements(app)

  expect_length(reqs$direct, 2)
  expect_match(reqs$direct[1], "Great_Tables")
  expect_match(reqs$direct[2], "mylib")
  # pytest is not a dependency of the app, so its source does not matter.
  expect_false(any(grepl("pytest", reqs$direct)))
  expect_equal(reqs$requirements, c("pandas==2.2.3", "shiny"))
})

test_that("a uv index source is reported with its index", {
  app <- local_py_app("pyproject.toml", c(
    "[project]",
    "dependencies = [\"torch\", \"shiny\"]",
    "[tool.uv.sources]",
    "torch = { index = \"pytorch-cpu\" }"
  ))

  reqs <- read_py_requirements(app)

  expect_equal(reqs$indexed, c(torch = "pytorch-cpu"))
  expect_equal(reqs$direct, character(0))
  expect_equal(reqs$requirements, c("torch", "shiny"))
})

test_that("an export stops on a Python requirement it cannot install from an index", {
  app <- local_py_app("requirements.txt", c(
    "great-tables @ git+https://github.com/posit-dev/great-tables",
    "shiny"
  ))

  err <- expect_error(
    resolve_app_dependencies(app, "py-shiny", "bundled", list()),
    class = "shinyelectron_python_direct_reference"
  )
  expect_match(conditionMessage(err), "great-tables", fixed = TRUE)
})

test_that("an export warns about pip options it does not read", {
  app <- local_py_app("requirements.txt", c(
    "--extra-index-url https://example.com/simple",
    "shiny"
  ))

  expect_warning(
    resolve_app_dependencies(app, "py-shiny", "bundled", list()),
    class = "shinyelectron_python_requirements_ignored"
  )
})

test_that("an export warns about a package that comes from a uv index", {
  app <- local_py_app("pyproject.toml", c(
    "[project]",
    "dependencies = [\"torch\", \"shiny\"]",
    "[tool.uv.sources]",
    "torch = { index = \"pytorch-cpu\" }"
  ))

  expect_warning(
    resolve_app_dependencies(app, "py-shiny", "bundled", list()),
    class = "shinyelectron_python_uv_index"
  )
})

test_that("resolved Python dependencies carry the pins and the declared packages", {
  app <- local_py_app("requirements.txt", c("pandas==2.2.3", "shiny"))
  config <- list(dependencies = list(python = list(packages = list("plotly>=5"))))

  deps <- resolve_app_dependencies(app, "py-shiny", "bundled", config)

  expect_equal(deps$packages, c("pandas", "plotly", "shiny"))
  expect_equal(deps$requirements, c("pandas==2.2.3", "shiny", "plotly>=5"))
})

test_that("the dependency manifest lists the Python requirement specs", {
  manifest <- jsonlite::fromJSON(generate_dependency_manifest(
    packages = c("pandas", "shiny"), language = "python",
    requirements = c("pandas==2.2.3", "shiny")
  ))

  expect_equal(manifest$packages, c("pandas", "shiny"))
  expect_equal(manifest$requirements, c("pandas==2.2.3", "shiny"))
})

test_that("pip gets the first index URL and every other one as an extra", {
  expect_equal(
    pip_index_args(list("https://a.example/simple", "https://b.example/simple",
                        "https://c.example/simple")),
    c("-i", "https://a.example/simple",
      "--extra-index-url", "https://b.example/simple",
      "--extra-index-url", "https://c.example/simple")
  )
  expect_equal(pip_index_args(NULL), c("-i", "https://pypi.org/simple"))
})

test_that("embed_python_runtime installs the requirement specs from every index", {
  skip_if_not_installed("mockery")
  out <- withr::local_tempdir()
  run <- mockery::mock(list(status = 0L, stdout = "", stderr = ""))
  mockery::stub(embed_python_runtime, "install_python_standalone", function(...) out)
  mockery::stub(embed_python_runtime, "copy_dir_contents", function(...) invisible())
  mockery::stub(embed_python_runtime, "python_executable", function(...) "python3")
  mockery::stub(embed_python_runtime, "processx::run", run)

  embed_python_runtime(
    output_dir = out, packages = c("pandas==2.2.3", "shiny"),
    index_urls = c("https://a.example/simple", "https://b.example/simple"),
    version = "3.12.0", platform = "mac", arch = "arm64", verbose = FALSE
  )

  pip_args <- mockery::mock_args(run)[[1]][[2]]
  expect_equal(pip_args[pip_args %in% c("pandas==2.2.3", "shiny")],
               c("pandas==2.2.3", "shiny"))
  expect_equal(pip_args[which(pip_args == "--extra-index-url") + 1],
               "https://b.example/simple")
})

test_that("the container Dockerfile installs each Python requirement as one argument", {
  skip_on_os("windows")
  out <- withr::local_tempdir()
  dir.create(file.path(out, "src", "app"), recursive = TRUE)
  dockerfiles <- file.path(out, "dockerfiles")
  dir.create(dockerfiles)
  writeLines("FROM python:3.12-slim", file.path(dockerfiles, "Dockerfile"))
  writeLines(generate_dependency_manifest(
    packages = c("numpy", "pandas"), language = "python",
    index_urls = list("https://a.example/simple", "https://b.example/simple"),
    requirements = c("pandas==2.2.3", "numpy==2.4.6 ; python_full_version < '3.12'")
  ), file.path(out, "src", "app", "dependencies.json"))

  bake_dockerfile_dependencies(out, dockerfiles)

  run <- grep("pip install", readLines(file.path(dockerfiles, "Dockerfile")), value = TRUE)
  expect_length(run, 1)
  # Let the shell split the command, printing one argument per line.
  cmd <- sub("RUN pip install --no-cache-dir", "printf '%s\\n'", run, fixed = TRUE)
  args <- processx::run("sh", c("-c", cmd))$stdout
  expect_equal(strsplit(args, "\n")[[1]], c(
    "-i", "https://a.example/simple",
    "--extra-index-url", "https://b.example/simple",
    "pandas==2.2.3", "numpy==2.4.6 ; python_full_version < '3.12'"
  ))
})

# --- R packages and the configured repositories ---

test_that("R packages on the repositories pass the check", {
  repo <- local_cran_repo(c("shiny", "ggplot2"))

  expect_silent(check_r_packages_on_repos(c("ggplot2", "shiny"), repo, "system"))
})

test_that("R packages missing from the repositories stop the export", {
  repo <- local_cran_repo("shiny")
  lib <- local_fake_library(list())

  err <- expect_error(
    check_r_packages_on_repos(c("inhouse", "shiny"), repo, "system", lib.loc = lib),
    class = "shinyelectron_r_packages_unavailable"
  )
  expect_match(conditionMessage(err), "inhouse", fixed = TRUE)
  expect_false(grepl("shiny", conditionMessage(err), fixed = TRUE))
})

test_that("a package R would hide on this system still counts as on the repository", {
  repo <- local_cran_repo(c("shiny", "winonly"), fields = c(winonly = "OS_type: windows"))
  skip_if(.Platform$OS.type == "windows", "OS_type: windows hides nothing here")

  expect_silent(check_r_packages_on_repos(c("shiny", "winonly"), repo, "system"))
})

test_that("an unreachable repository warns and skips the check", {
  repo <- "file:///shinyelectron-no-such-repository"

  expect_warning(
    check_r_packages_on_repos("inhouse", repo, "system"),
    class = "shinyelectron_repos_unreachable"
  )
})

test_that("r_package_origin says where the installed copy came from", {
  lib <- local_fake_library(list(
    ghpkg = c("RemoteType: github", "RemoteUsername: me", "RemoteRepo: ghpkg"),
    gitpkg = c("RemoteType: git2r", "RemoteUrl: https://git.example.com/gitpkg.git"),
    univpkg = "Repository: https://me.r-universe.dev",
    oldpkg = "Repository: CRAN",
    remotelocal = c("RemoteType: local", "RemoteUrl: /home/me/remotelocal"),
    localpkg = character()
  ))

  expect_equal(r_package_origin("ghpkg", lib), "installed here from GitHub (me/ghpkg)")
  expect_equal(r_package_origin("gitpkg", lib),
               "installed here from https://git.example.com/gitpkg.git")
  expect_equal(r_package_origin("univpkg", lib),
               "installed here from https://me.r-universe.dev")
  expect_equal(r_package_origin("oldpkg", lib), "installed here from CRAN")
  expect_equal(r_package_origin("remotelocal", lib), "installed here from a local source")
  expect_equal(r_package_origin("localpkg", lib), "installed here from a local source")
  expect_equal(r_package_origin("nopkg", lib), "not installed here")
})

test_that("an R export stops when the app uses a package the repositories lack", {
  skip_if_not_installed("renv")
  app <- withr::local_tempdir()
  writeLines(c("library(shiny)", "library(inhouse)"), file.path(app, "app.R"))
  config <- list(dependencies = list(r = list(repos = list(local_cran_repo("shiny")))))

  expect_error(
    resolve_app_dependencies(app, "r-shiny", "auto-download", config),
    class = "shinyelectron_r_packages_unavailable"
  )
})

test_that("app_check() fails when the app uses an R package the repositories lack", {
  local_no_electron_lookup()
  skip_if_not_installed("renv")
  app <- withr::local_tempdir()
  writeLines(c("library(shiny)", "library(inhouse)"), file.path(app, "app.R"))
  writeLines(c("dependencies:", "  r:", "    repos:",
               paste0("      - \"", local_cran_repo("shiny"), "\"")),
             file.path(app, "_shinyelectron.yml"))

  result <- app_check(app, runtime_strategy = "auto-download", verbose = FALSE)

  expect_false(result$pass)
  expect_match(paste(result$errors, collapse = "\n"), "inhouse", fixed = TRUE)
  expect_no_match(paste(result$warnings, collapse = "\n"), "Dependency check", fixed = TRUE)
})

test_that("app_check() fails on a Python requirement it cannot install from an index", {
  local_no_electron_lookup()
  app <- local_py_app("requirements.txt", c(
    "great-tables @ git+https://github.com/posit-dev/great-tables",
    "shiny"
  ))

  result <- app_check(app, runtime_strategy = "bundled", verbose = FALSE)

  expect_false(result$pass)
  expect_match(paste(result$errors, collapse = "\n"), "great-tables", fixed = TRUE)
  expect_no_match(paste(result$warnings, collapse = "\n"), "Dependency check", fixed = TRUE)
})

test_that("a local package covers a package the repositories lack", {
  skip_if_not_installed("renv")
  app <- withr::local_tempdir()
  writeLines(c("library(shiny)", "library(inhouse)"), file.path(app, "app.R"))
  src <- file.path(withr::local_tempdir(), "inhouse")
  dir.create(src)
  writeLines(c("Package: inhouse", "Version: 0.1.0"), file.path(src, "DESCRIPTION"))
  config <- list(dependencies = list(r = list(
    repos = list(local_cran_repo("shiny")),
    local_packages = resolve_local_packages(list(src), base_dir = app)
  )))

  deps <- resolve_app_dependencies(app, "r-shiny", "bundled", config)

  expect_equal(deps$packages, c("inhouse", "shiny"))
})

# A two-app Python suite whose root requirements.txt holds `requirements`
# (`NULL` for no root file). `app_requirements` gives the apps "one" and "two"
# a requirements.txt of their own.
local_py_suite <- function(requirements, app_requirements = list(),
                           env = parent.frame()) {
  suite <- withr::local_tempdir(.local_envir = env)
  for (id in c("one", "two")) {
    dir.create(file.path(suite, "apps", id), recursive = TRUE)
    writeLines("from shiny import App, ui\napp = App(ui.page_fluid(), None)",
               file.path(suite, "apps", id, "app.py"))
    if (!is.null(app_requirements[[id]])) {
      writeLines(app_requirements[[id]],
                 file.path(suite, "apps", id, "requirements.txt"))
    }
  }
  if (!is.null(requirements)) {
    writeLines(requirements, file.path(suite, "requirements.txt"))
  }
  suite
}

py_suite_config <- list(
  app = list(name = "Suite", version = "1.0.0"),
  build = list(type = "py-shiny", runtime_strategy = "system"),
  apps = list(
    list(id = "one", name = "One", path = "./apps/one"),
    list(id = "two", name = "Two", path = "./apps/two")
  )
)

test_that("a Python suite's app manifests carry the suite's pins", {
  local_no_electron_lookup()
  suite <- local_py_suite(c("pandas==2.2.3", "shiny"))
  destdir <- file.path(withr::local_tempdir(), "out")

  export_multi_app(appdir = suite, destdir = destdir, config = py_suite_config,
                   app_name = "Suite", runtime_strategy = "system",
                   build = FALSE, overwrite = TRUE, verbose = FALSE)

  manifest <- jsonlite::fromJSON(file.path(destdir, "apps", "one", "dependencies.json"))
  expect_equal(manifest$requirements, c("pandas==2.2.3", "shiny"))
})

test_that("a Python suite stops on a requirement it cannot install from an index", {
  local_no_electron_lookup()
  suite <- local_py_suite("git+https://github.com/me/other.git#egg=other")
  destdir <- file.path(withr::local_tempdir(), "out")

  expect_error(
    export_multi_app(appdir = suite, destdir = destdir, config = py_suite_config,
                     app_name = "Suite", runtime_strategy = "system",
                     build = FALSE, overwrite = TRUE, verbose = FALSE),
    class = "shinyelectron_python_direct_reference"
  )
})

test_that("the container image installs R packages from its CRAN and the other configured repositories", {
  local_mocked_bindings(query_sysreqs = function(...) character(0))
  out <- withr::local_tempdir()
  dir.create(file.path(out, "src", "app"), recursive = TRUE)
  dockerfiles <- file.path(out, "dockerfiles")
  dir.create(dockerfiles)
  writeLines("FROM rocker/r-ver:4.6.0", file.path(dockerfiles, "Dockerfile"))
  writeLines(generate_dependency_manifest(
    packages = c("inhouse", "shiny"), language = "r",
    repos = list("https://cloud.r-project.org", "https://me.r-universe.dev")
  ), file.path(out, "src", "app", "dependencies.json"))

  bake_dockerfile_dependencies(out, dockerfiles)

  run <- grep("install.packages", readLines(file.path(dockerfiles, "Dockerfile")),
              value = TRUE, fixed = TRUE)
  # Run the image's R code with rocker's repository option and a stand-in
  # for install.packages() that returns what it was given.
  code <- sub('^RUN R -e "(.*)"$', "\\1", run)
  withr::local_options(repos = c(CRAN = "https://p3m.example/cran"))
  got <- eval(parse(text = code)[[1]], list(
    install.packages = function(pkgs, repos = getOption("repos"), ...) {
      list(pkgs = pkgs, repos = unname(repos))
    }
  ), baseenv())
  expect_equal(got$pkgs, c("inhouse", "shiny"))
  expect_equal(got$repos, c("https://p3m.example/cran", "https://me.r-universe.dev"))
})

# --- Requirements the app does not use ---

test_that("with auto_detect off, the requirements file is not checked", {
  app <- local_py_app("requirements.txt", c(
    "git+https://github.com/me/other.git",
    "--extra-index-url https://example.com/simple",
    "shiny"
  ))
  config <- list(dependencies = list(
    auto_detect = FALSE,
    python = list(packages = list("shiny"))
  ))

  expect_no_warning(
    deps <- resolve_app_dependencies(app, "py-shiny", "system", config)
  )
  expect_equal(deps$packages, "shiny")
})

test_that("the error for a requirement off the index names the auto_detect setting", {
  app <- local_py_app("requirements.txt", c("-e .", "shiny"))

  err <- expect_error(
    resolve_app_dependencies(app, "py-shiny", "system", list()),
    class = "shinyelectron_python_direct_reference"
  )
  expect_match(conditionMessage(err), "dependencies.auto_detect", fixed = TRUE)
})

test_that("a Python suite of shinylive apps does not read the suite's requirements", {
  local_no_electron_lookup()
  suite <- local_py_suite(c("-e .", "shiny"))
  destdir <- file.path(withr::local_tempdir(), "out")
  local_mocked_bindings(
    convert_py_to_shinylive = function(appdir, output_dir, subdir = NULL, ...) {
      dir.create(file.path(output_dir, subdir), recursive = TRUE)
      invisible(output_dir)
    }
  )
  config <- py_suite_config
  config$build$runtime_strategy <- "shinylive"

  expect_no_error(
    export_multi_app(appdir = suite, destdir = destdir, config = config,
                     app_name = "Suite", runtime_strategy = "shinylive",
                     build = FALSE, overwrite = TRUE, verbose = FALSE)
  )
})

# --- Paths and pip options in requirements.txt ---

test_that("a path with no leading dot is a requirement an index cannot install", {
  app <- local_py_app("requirements.txt", c(
    "vendor/mypkg",
    "wheels\\other",
    "shiny ; platform_release != 'a/b'"
  ))

  reqs <- read_py_requirements(app)

  expect_equal(reqs$direct, c("vendor/mypkg", "wheels\\other"))
  expect_equal(reqs$requirements, "shiny ; platform_release != 'a/b'")
})

test_that("an included requirements file is reported as not read", {
  app <- local_py_app("requirements.txt", c(
    "-r requirements/base.txt",
    "-c constraints.txt",
    "shiny"
  ))

  w <- expect_warning(
    resolve_app_dependencies(app, "py-shiny", "bundled", list()),
    class = "shinyelectron_python_requirements_ignored"
  )
  expect_match(conditionMessage(w), "are not read", fixed = TRUE)
  expect_no_match(conditionMessage(w), "index_urls", fixed = TRUE)
})

test_that("an index option is answered with the index setting", {
  app <- local_py_app("requirements.txt", c(
    "--extra-index-url https://example.com/simple",
    "shiny"
  ))

  w <- expect_warning(
    resolve_app_dependencies(app, "py-shiny", "bundled", list()),
    class = "shinyelectron_python_requirements_ignored"
  )
  expect_match(conditionMessage(w), "index_urls", fixed = TRUE)
  expect_no_match(conditionMessage(w), "are not read", fixed = TRUE)
})

test_that("a suite requirements.txt that holds only pip options is still reported", {
  local_no_electron_lookup()
  suite <- local_py_suite("-r base.txt",
                          app_requirements = list(one = "shiny", two = "shiny"))
  destdir <- file.path(withr::local_tempdir(), "out")

  expect_warning(
    export_multi_app(appdir = suite, destdir = destdir, config = py_suite_config,
                     app_name = "Suite", runtime_strategy = "system",
                     build = FALSE, overwrite = TRUE, verbose = FALSE),
    class = "shinyelectron_python_requirements_ignored"
  )
})

# --- The shape of the manifest ---

test_that("the dependency manifest writes a single index or repository as a list", {
  local_mocked_bindings(query_sysreqs = function(...) character(0))

  py <- jsonlite::fromJSON(generate_dependency_manifest(
    packages = "shiny", language = "python",
    index_urls = "https://mirror.example/simple"
  ), simplifyVector = FALSE)
  r <- jsonlite::fromJSON(generate_dependency_manifest(
    packages = "shiny", language = "r", repos = "https://a.example"
  ), simplifyVector = FALSE)

  expect_equal(py$index_urls, list("https://mirror.example/simple"))
  expect_equal(r$repos, list("https://a.example"))
})

# --- Repositories that cannot be read ---

test_that("an unreachable repository does not hide packages found on another", {
  repos <- list("file:///no-such-repository",
                local_cran_repo(c("ggplot2", "jsonlite")))

  expect_silent(check_r_packages_on_repos(c("ggplot2", "jsonlite"), repos, "system"))
})

test_that("an unreachable repository warns with the packages it left unchecked", {
  repos <- list("file:///no-such-repository", local_cran_repo("ggplot2"))

  w <- expect_warning(
    check_r_packages_on_repos(c("inhouse", "ggplot2"), repos, "system"),
    class = "shinyelectron_repos_unreachable"
  )
  expect_match(conditionMessage(w), "inhouse", fixed = TRUE)
  expect_no_match(conditionMessage(w), "ggplot2", fixed = TRUE)
})

test_that("an empty repository is read, not skipped", {
  empty <- local_cran_repo(character())
  lib <- local_fake_library(list())

  expect_error(
    check_r_packages_on_repos("inhouse", empty, "system", lib.loc = lib),
    class = "shinyelectron_r_packages_unavailable"
  )
})

# --- Local packages outside a bundled build ---

test_that("a local package does not cover a missing package outside a bundled build", {
  skip_if_not_installed("renv")
  app <- withr::local_tempdir()
  writeLines(c("library(shiny)", "library(inhouse)"), file.path(app, "app.R"))
  src <- file.path(withr::local_tempdir(), "inhouse")
  dir.create(src)
  writeLines(c("Package: inhouse", "Version: 0.1.0"), file.path(src, "DESCRIPTION"))
  config <- list(dependencies = list(r = list(
    repos = list(local_cran_repo("shiny")),
    local_packages = resolve_local_packages(list(src), base_dir = app)
  )))

  expect_error(
    resolve_app_dependencies(app, "r-shiny", "container", config),
    class = "shinyelectron_r_packages_unavailable"
  )
})

# --- Checks run before the previous build is removed ---

test_that("an R export that fails its package check leaves the previous build", {
  local_no_electron_lookup()
  skip_if_not_installed("renv")
  app <- withr::local_tempdir()
  writeLines(c("library(shiny)", "library(inhouse)",
               "shinyApp(fluidPage(), function(input, output) {})"),
             file.path(app, "app.R"))
  writeLines(c("dependencies:", "  r:", "    repos:",
               paste0("      - \"", local_cran_repo("shiny"), "\"")),
             file.path(app, "_shinyelectron.yml"))
  out <- file.path(withr::local_tempdir(), "out")
  dir.create(out)
  writeLines("previous build", file.path(out, "keep.txt"))

  expect_error(
    export(appdir = app, destdir = out, app_type = "r-shiny",
           runtime_strategy = "system", overwrite = TRUE, build = FALSE,
           verbose = FALSE),
    class = "shinyelectron_r_packages_unavailable"
  )
  expect_true(file.exists(file.path(out, "keep.txt")))
})

test_that("a Python suite that fails its requirements check leaves the previous build", {
  local_no_electron_lookup()
  suite <- local_py_suite("git+https://github.com/me/other.git#egg=other")
  out <- file.path(withr::local_tempdir(), "out")
  dir.create(out)
  writeLines("previous build", file.path(out, "keep.txt"))

  expect_error(
    export_multi_app(appdir = suite, destdir = out, config = py_suite_config,
                     app_name = "Suite", runtime_strategy = "system",
                     build = FALSE, overwrite = TRUE, verbose = FALSE),
    class = "shinyelectron_python_direct_reference"
  )
  expect_true(file.exists(file.path(out, "keep.txt")))
})

# --- Pins that disagree across the apps of a bundled suite ---

test_that("apps that pin different versions of a package are a conflict", {
  err <- expect_error(
    check_py_pin_conflicts(list(
      One = c("pandas==2.0.3", "shiny"),
      Two = c("pandas==2.2.3", "shiny")
    )),
    class = "shinyelectron_python_pin_conflict"
  )
  expect_match(conditionMessage(err), "pandas", fixed = TRUE)
  expect_no_match(conditionMessage(err), "shiny", fixed = TRUE)
})

test_that("apps that agree on a pin, or pin under different markers, are not a conflict", {
  expect_silent(check_py_pin_conflicts(list(
    One = c("pandas==2.2.3", "numpy==2.4.6 ; python_version < '3.12'"),
    Two = c("Pandas==2.2.3", "numpy==2.5.4 ; python_version >= '3.12'", "shiny>=1.8")
  )))
})

test_that("a bundled Python suite stops when its apps pin different versions", {
  local_no_electron_lookup()
  suite <- local_py_suite(NULL, app_requirements = list(
    one = c("pandas==2.0.3", "shiny"),
    two = c("pandas==2.2.3", "shiny")
  ))
  destdir <- file.path(withr::local_tempdir(), "out")
  config <- py_suite_config
  config$build$runtime_strategy <- "bundled"

  expect_error(
    suppressWarnings(
      export_multi_app(appdir = suite, destdir = destdir, config = config,
                       app_name = "Suite", runtime_strategy = "bundled",
                       build = FALSE, overwrite = TRUE, verbose = FALSE)
    ),
    class = "shinyelectron_python_pin_conflict"
  )
})

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.