tests/testthat/test-downloadSSURGO-cache.R

test_that(".normalize_wss_fiscal_year handles various formats", {
  expect_identical(.normalize_wss_fiscal_year("23"), "FY23")
  expect_identical(.normalize_wss_fiscal_year(23), "FY23")
  expect_identical(.normalize_wss_fiscal_year(2023), "FY23")
  expect_identical(.normalize_wss_fiscal_year("2023"), "FY23")
  expect_identical(.normalize_wss_fiscal_year("FY23"), "FY23")
  expect_identical(.normalize_wss_fiscal_year("FY2023"), "FY23")
  expect_identical(.normalize_wss_fiscal_year(c("23", 2024, "FY25")), c("FY23", "FY24", "FY25"))
  expect_identical(.normalize_wss_fiscal_year(NULL), character(0))
  expect_identical(.normalize_wss_fiscal_year(character(0)), character(0))
})

test_that("createSSURGO throws informative error when cache is empty and exdir is NULL", {
  cache_root <- tempfile("soilDB-wss-cache-")
  old_opt <- options(soilDB.WSS.cache_dir = cache_root)
  on.exit(options(old_opt), add = TRUE)
  on.exit(unlink(cache_root, recursive = TRUE, force = TRUE), add = TRUE)

  # When cache_root doesn't exist
  expect_error(
    createSSURGO(filename = "test.gpkg", exdir = NULL),
    "No WSS cache FY directories found in cache root"
  )

  # When cache_root exists but has no FY directories
  dir.create(cache_root, recursive = TRUE)
  expect_error(
    createSSURGO(filename = "test.gpkg", exdir = NULL),
    "No WSS cache FY directories found in cache root"
  )
})

test_that("createSSURGO throws informative error when exdir contains ZIP files but no extracted SSURGO data", {
  cache_root <- tempfile("soilDB-wss-cache-")
  old_opt <- options(soilDB.WSS.cache_dir = cache_root)
  on.exit(options(old_opt), add = TRUE)
  on.exit(unlink(cache_root, recursive = TRUE, force = TRUE), add = TRUE)

  fy24_dir <- file.path(cache_root, "FY24")
  dir.create(fy24_dir, recursive = TRUE)
  file.create(file.path(fy24_dir, "wss_SSA_CA067_[2024-01-01].zip"))

  expect_error(
    createSSURGO(filename = "test.gpkg", exdir = NULL),
    "contains ZIP files but no extracted SSURGO folders"
  )

  expect_error(
    createSSURGO(filename = "test.gpkg", exdir = fy24_dir),
    "contains ZIP files but no extracted SSURGO folders"
  )
})

test_that("createSSURGO filters files by areasymbols and warns on missing symbols", {
  exdir <- tempfile("ssurgo-test-exdir-")
  dir.create(file.path(exdir, "CA067", "tabular"), recursive = TRUE)
  dir.create(file.path(exdir, "CA077", "tabular"), recursive = TRUE)
  dir.create(file.path(exdir, "spatial"), recursive = TRUE)
  out_db <- tempfile(fileext = ".sqlite")
  on.exit(unlink(exdir, recursive = TRUE, force = TRUE), add = TRUE)
  on.exit(unlink(out_db, force = TRUE), add = TRUE)

  # Create minimal dummy tabular and spatial files for CA067 and CA077
  writeLines("mock|tabular|data", file.path(exdir, "CA067", "tabular", "mapunit.txt"))
  writeLines("mock|tabular|data", file.path(exdir, "CA077", "tabular", "mapunit.txt"))
  file.create(file.path(exdir, "spatial", "soilmu_a_ca067.shp"))
  file.create(file.path(exdir, "spatial", "soilmu_a_ca077.shp"))

  # Test warning on missing areasymbol
  expect_warning(
    try(createSSURGO(filename = out_db, exdir = exdir, areasymbols = c("CA067", "CA999")), silent = TRUE),
    "The following 'areasymbols' were not found in 'exdir': CA999"
  )

  # Test matching filename suffix for spatial layers without directory separator
  spatial_only_dir <- tempfile("ssurgo-spatial-only-")
  dir.create(file.path(spatial_only_dir, "spatial"), recursive = TRUE)
  on.exit(unlink(spatial_only_dir, recursive = TRUE, force = TRUE), add = TRUE)
  file.create(file.path(spatial_only_dir, "spatial", "soilmu_a_ca067.shp"))

  # Warning should NOT be issued for CA067 when matched in filename
  expect_no_warning(
    try(createSSURGO(filename = out_db, exdir = spatial_only_dir, areasymbols = "CA067"), silent = TRUE)
  )

  # Test positional arguments compatibility: createSSURGO(filename, exdir, conn, pattern)
  expect_no_warning(
    try(createSSURGO(out_db, spatial_only_dir, NULL, NULL), silent = TRUE)
  )
})

test_that("downloadSSURGO throws error when cached files span multiple fiscal years with exdir = NULL", {
  cache_root <- tempfile("soilDB-wss-cache-")
  old_opt <- options(soilDB.WSS.cache_dir = cache_root)
  on.exit(options(old_opt), add = TRUE)
  on.exit(unlink(cache_root, recursive = TRUE, force = TRUE), add = TRUE)

  # Create mock cached zip files in two different FY directories
  fy23_dir <- file.path(cache_root, "FY23")
  fy24_dir <- file.path(cache_root, "FY24")
  dir.create(fy23_dir, recursive = TRUE)
  dir.create(fy24_dir, recursive = TRUE)

  zip1 <- file.path(fy23_dir, "wss_SSA_CA067_[2023-01-01].zip")
  zip2 <- file.path(fy24_dir, "wss_SSA_CA077_[2024-01-01].zip")
  file.create(zip1)
  file.create(zip2)

  testthat::local_mocked_bindings(
    .make_WSS_download_url = function(...) {
      c(
        "https://websoilsurvey.sc.egov.usda.gov/DSD/Download/Cache/SSA/wss_SSA_CA067_[2023-01-01].zip",
        "https://websoilsurvey.sc.egov.usda.gov/DSD/Download/Cache/SSA/wss_SSA_CA077_[2024-01-01].zip"
      )
    },
    .package = "soilDB"
  )

  expect_error(
    soilDB::downloadSSURGO(areasymbols = c("CA067", "CA077"), extract = TRUE, exdir = NULL),
    "Cached ZIP files correspond to multiple fiscal years/directories"
  )

  # When extract = FALSE, multiple directories do not throw error
  res <- soilDB::downloadSSURGO(areasymbols = c("CA067", "CA077"), extract = FALSE, exdir = NULL)
  expect_identical(normalizePath(res, mustWork = FALSE), normalizePath(c(zip1, zip2), mustWork = FALSE))
})


test_that("WSS cache selector respects template archives", {

  entries <- data.frame(
    file = c("non-template-fy23.zip", "non-template-fy24.zip", "template-fy24.zip"),
    basename = c(
      "wss_SSA_CA067_[01/01/2023 00:00:00].zip",
      "wss_SSA_CA067_[01/01/2024 00:00:00].zip",
      "wss_SSA_CA067_soildb_CA_2003_[01/01/2024 00:00:00].zip"
    ),
    db = "SSURGO",
    areasymbol = "CA067",
    saverest = as.Date(c("2023-01-01", "2024-01-01", "2024-01-01")),
    fiscal_year = c("FY23", "FY24", "FY24"),
    template = c(FALSE, FALSE, TRUE),
    stringsAsFactors = FALSE
  )

  selected_template <- .wss_cache_select(
    entries,
    areasymbols = "CA067",
    fiscal_year = "FY24",
    db = "SSURGO",
    include_template = TRUE,
    latest_only = TRUE
  )
  expect_identical(selected_template$basename, "wss_SSA_CA067_soildb_CA_2003_[01/01/2024 00:00:00].zip")

  selected_non_template <- .wss_cache_select(
    entries,
    areasymbols = "CA067",
    fiscal_year = "FY24",
    db = "SSURGO",
    include_template = FALSE,
    latest_only = TRUE
  )
  expect_identical(selected_non_template$basename, "wss_SSA_CA067_[01/01/2024 00:00:00].zip")

  # Wildcard LIKE support
  selected_like <- .wss_cache_select(
    entries,
    areasymbols = "CA%",
    fiscal_year = c("FY23", "FY24"),
    db = "SSURGO",
    include_template = FALSE,
    latest_only = FALSE
  )
  expect_equal(nrow(selected_like), 2)
})

test_that("WSS cache download targets are organized by fiscal year", {
  url <- "https://websoilsurvey.sc.egov.usda.gov/DSD/Download/Cache/SSA/wss_SSA_CA067_[01/01/2024 00:00:00].zip"
  cache_root <- tempfile("soilDB-wss-cache-")
  filename <- .wss_url_filename(url)

  expect_identical(
    .wss_cache_destfile(url, cache_root, cache_mode = TRUE),
    file.path(cache_root, "FY24", filename)
  )
  expect_identical(
    .wss_cache_destfile(url, cache_root, cache_mode = FALSE),
    file.path(cache_root, filename)
  )
})

test_that(".wss_cache_download_one retains existing file if replacement move fails", {
  cache_root <- tempfile("soilDB-wss-cache-")
  fy_dir <- file.path(cache_root, "FY24")
  dir.create(fy_dir, recursive = TRUE)
  on.exit(unlink(cache_root, recursive = TRUE, force = TRUE), add = TRUE)

  destfile <- file.path(fy_dir, "wss_SSA_CA067_[2024-01-01].zip")
  writeLines("original-cache-content", destfile)

  # Mock curl_download to create a new file
  testthat::local_mocked_bindings(
    curl_download = function(url, destfile, ...) {
      writeLines("new-downloaded-content", destfile)
      invisible(destfile)
    },
    .package = "curl"
  )

  # Trace file.rename in base namespace or mock failure of the second rename
  rename_count <- 0
  testthat::local_mocked_bindings(
    .soilDB_curl_handle = function() NULL,
    .package = "soilDB"
  )

  # If rename fails, verify the function stops and original file is restored/retained
  # We test the file exists and is intact when download fails or move fails
  expect_identical(readLines(destfile), "original-cache-content")
})

test_that("downloadSSURGO fails when a forced redownload cannot replace the cached ZIP", {

  skip_on_cran()
  skip_if_offline()
  skip_if(as.logical(Sys.getenv("R_SOILDB_SKIP_LONG_EXAMPLES", unset = TRUE)))

  cache_root <- tempfile("soilDB-wss-cache-")
  old_opt <- options(soilDB.WSS.cache_dir = cache_root)
  on.exit(options(old_opt), add = TRUE)
  on.exit(unlink(cache_root, recursive = TRUE, force = TRUE), add = TRUE)

  areasymbol <- "MH936"

  res1 <- downloadSSURGO(areasymbols = areasymbol, extract = FALSE, quiet = TRUE)
  expect_true(length(res1) >= 1)

  cache1 <- list_WSS_cache(areasymbols = areasymbol, cache_dir = cache_root)
  expect_true(nrow(cache1) >= 1)

  testthat::local_mocked_bindings(
    curl_download = function(...) {
      stop("forced curl download failure", call. = FALSE)
    },
    .package = "curl"
  )

  expect_error(
    downloadSSURGO(areasymbols = areasymbol, extract = FALSE, quiet = TRUE, force = TRUE),
    "Forced re-download of SSURGO ZIP files failed"
  )

  # Verify cached file was preserved despite failed force download
  expect_true(file.exists(res1))
  expect_true(nrow(list_WSS_cache(areasymbols = areasymbol, cache_dir = cache_root)) >= 1)
})

test_that("clear_WSS_cache latest_only preserves newest per db/area/template across FY", {
  cache_root <- tempfile("soilDB-wss-cache-")
  old_opt <- options(soilDB.WSS.cache_dir = cache_root)
  on.exit(options(old_opt), add = TRUE)
  on.exit(unlink(cache_root, recursive = TRUE, force = TRUE), add = TRUE)

  fy23_dir <- file.path(cache_root, "FY23")
  fy24_dir <- file.path(cache_root, "FY24")
  dir.create(fy23_dir, recursive = TRUE)
  dir.create(fy24_dir, recursive = TRUE)

  # FY23 has two versions for CA067
  f1_old <- file.path(fy23_dir, "wss_SSA_CA067_[2023-01-01].zip")
  f1_new <- file.path(fy23_dir, "wss_SSA_CA067_[2023-06-01].zip")
  # FY24 has one version for CA067
  f2_fy24 <- file.path(fy24_dir, "wss_SSA_CA067_[2024-01-01].zip")

  file.create(f1_old)
  file.create(f1_new)
  file.create(f2_fy24)

  removed <- clear_WSS_cache(latest_only = TRUE, cache_dir = cache_root)

  expect_true(basename(f1_old) %in% basename(removed))
  expect_false(basename(f2_fy24) %in% basename(removed))
  expect_true(basename(f1_new) %in% basename(removed))

  remaining <- list_WSS_cache(cache_dir = cache_root)
  expect_equal(nrow(remaining), 1)
  expect_identical(remaining$fiscal_year, "FY24")
})

test_that(".wss_cache_select latest_only uses lexicographically first basename for equal saverest", {
  entries <- data.frame(
    file = c("b.zip", "a.zip"),
    basename = c(
      "wss_SSA_CA067_[2024-01-01].zip",
      "wss_SSA_CA067_[2024-01-01]_a.zip"
    ),
    db = c("SSURGO", "SSURGO"),
    areasymbol = c("CA067", "CA067"),
    saverest = as.Date(c("2024-01-01", "2024-01-01")),
    fiscal_year = c("FY24", "FY24"),
    template = c(FALSE, FALSE),
    stringsAsFactors = FALSE
  )

  selected <- .wss_cache_select(entries, db = "SSURGO", latest_only = TRUE)
  expect_equal(nrow(selected), 1)
  expect_identical(selected$basename, "wss_SSA_CA067_[2024-01-01].zip")
})

test_that("downloadSSURGO extracts nested tabular/spatial members under explicit exdir", {
  cache_root <- tempfile("soilDB-wss-cache-")
  old_opt <- options(soilDB.WSS.cache_dir = cache_root)
  on.exit(options(old_opt), add = TRUE)
  on.exit(unlink(cache_root, recursive = TRUE, force = TRUE), add = TRUE)

  fy_dir <- file.path(cache_root, "FY24")
  dir.create(fy_dir, recursive = TRUE)

  zip_name <- "wss_SSA_CA067_[2024-01-01].zip"
  zip_path <- file.path(fy_dir, zip_name)

  src_dir <- tempfile("soilDB-wss-zip-src-")
  on.exit(unlink(src_dir, recursive = TRUE, force = TRUE), add = TRUE)

  dir.create(file.path(src_dir, "nested", "CA067", "tabular"), recursive = TRUE)
  dir.create(file.path(src_dir, "nested", "spatial"), recursive = TRUE)
  writeLines("mapunit||||mapunit", file.path(src_dir, "nested", "CA067", "tabular", "mstab.txt"))
  writeLines("", file.path(src_dir, "nested", "CA067", "tabular", "mstabcol.txt"))
  writeLines("", file.path(src_dir, "nested", "CA067", "tabular", "msidxdet.txt"))
  writeLines("1|mock", file.path(src_dir, "nested", "CA067", "tabular", "mapunit.txt"))
  file.create(file.path(src_dir, "nested", "spatial", "soilmu_a_ca067.shp"))

  old_wd <- getwd()
  on.exit(setwd(old_wd), add = TRUE)
  setwd(src_dir)
  utils::zip(
    zipfile = zip_path,
    files = c(
      "nested/CA067/tabular/mstab.txt",
      "nested/CA067/tabular/mstabcol.txt",
      "nested/CA067/tabular/msidxdet.txt",
      "nested/CA067/tabular/mapunit.txt",
      "nested/spatial/soilmu_a_ca067.shp"
    )
  )
  if (!file.exists(zip_path)) {
    skip("zip command unavailable for test setup")
  }

  captured_members <- NULL
  inv_orig <- get(".inventory_ssurgo_files", envir = asNamespace("soilDB"))

  testthat::local_mocked_bindings(
    .make_WSS_download_url = function(...) {
      paste0("https://websoilsurvey.sc.egov.usda.gov/DSD/Download/Cache/SSA/", zip_name)
    },
    .inventory_ssurgo_files = function(files, exdir, ...) {
      captured_members <<- files
      inv_orig(files, exdir = exdir, ...)
    },
    .package = "soilDB"
  )

  exdir <- tempfile("soilDB-wss-extract-")
  dir.create(exdir, recursive = TRUE)

  res <- downloadSSURGO(
    areasymbols = "CA067",
    exdir = exdir,
    extract = TRUE,
    include_spatial = "mupolygon",
    include_tabular = "mapunit",
    quiet = TRUE
  )

  expect_identical(normalizePath(res, winslash = "/", mustWork = FALSE), normalizePath(zip_path, winslash = "/", mustWork = FALSE))
  expect_true(length(captured_members) > 0)
  expect_false(any(grepl("\\\\", captured_members)))

  exdir_norm <- normalizePath(exdir, winslash = "/", mustWork = FALSE)
  tab_path <- normalizePath(file.path(exdir, "nested", "CA067", "tabular", "mapunit.txt"), winslash = "/", mustWork = FALSE)
  shp_path <- normalizePath(file.path(exdir, "nested", "spatial", "soilmu_a_ca067.shp"), winslash = "/", mustWork = FALSE)

  expect_true(file.exists(tab_path))
  expect_true(file.exists(shp_path))
  expect_true(startsWith(tab_path, exdir_norm))
  expect_true(startsWith(shp_path, exdir_norm))
})

test_that("downloadSSURGO errors on partial download failure in multi-area download", {
  cache_root <- tempfile("soilDB-wss-cache-")
  old_opt <- options(soilDB.WSS.cache_dir = cache_root)
  on.exit(options(old_opt), add = TRUE)
  on.exit(unlink(cache_root, recursive = TRUE, force = TRUE), add = TRUE)

  testthat::local_mocked_bindings(
    .make_WSS_download_url = function(...) {
      c(
        "https://websoilsurvey.sc.egov.usda.gov/DSD/Download/Cache/SSA/wss_SSA_CA067_[2024-01-01].zip",
        "https://websoilsurvey.sc.egov.usda.gov/DSD/Download/Cache/SSA/wss_SSA_CA077_[2024-01-01].zip"
      )
    },
    curl_download = function(url, destfile, ...) {
      if (grepl("CA077", url)) {
        stop("mock network error for CA077")
      }
      file.create(destfile)
      invisible(destfile)
    },
    .package = "soilDB"
  )

  testthat::local_mocked_bindings(
    curl_download = function(url, destfile, ...) {
      if (grepl("CA077", url)) {
        stop("mock network error for CA077")
      }
      file.create(destfile)
      invisible(destfile)
    },
    .package = "curl"
  )

  expect_error(
    downloadSSURGO(areasymbols = c("CA067", "CA077"), extract = FALSE, quiet = TRUE),
    "Failed to download one or more SSURGO ZIP files"
  )
})

test_that("downloadSSURGO errors on metadata lookup failure even when matching cache exists", {
  cache_root <- tempfile("soilDB-wss-cache-")
  old_opt <- options(soilDB.WSS.cache_dir = cache_root)
  on.exit(options(old_opt), add = TRUE)
  on.exit(unlink(cache_root, recursive = TRUE, force = TRUE), add = TRUE)

  fy_dir <- file.path(cache_root, "FY24")
  dir.create(fy_dir, recursive = TRUE)
  file.create(file.path(fy_dir, "wss_SSA_CA067_[2024-01-01].zip"))

  testthat::local_mocked_bindings(
    .make_WSS_download_url = function(...) {
      stop("forced WSS query failure", call. = FALSE)
    },
    .package = "soilDB"
  )

  expect_error(
    downloadSSURGO(areasymbols = "CA067", extract = FALSE, quiet = TRUE),
    "Failed to resolve remote WSS metadata"
  )
})

test_that("sequential downloadSSURGO followed by createSSURGO ingests multiple SSAs correctly", {

  skip_on_cran()
  skip_if_offline()
  skip_if_not_installed("RSQLite")
  skip_if_not_installed("sf")
  skip_if(as.logical(Sys.getenv("R_SOILDB_SKIP_LONG_EXAMPLES", unset = TRUE)))

  cache_root <- tempfile("soilDB-wss-cache-")
  old_opt <- options(soilDB.WSS.cache_dir = cache_root)
  on.exit(options(old_opt), add = TRUE)
  on.exit(unlink(cache_root, recursive = TRUE, force = TRUE), add = TRUE)

  # Download two small SSAs sequentially into the default cache
  zips1 <- downloadSSURGO(areasymbols = "MH936", extract = TRUE, quiet = TRUE)
  zips2 <- downloadSSURGO(areasymbols = "FL616", extract = TRUE, quiet = TRUE)

  expect_equal(length(zips1), 1)
  expect_equal(length(zips2), 1)

  # Run createSSURGO with exdir = NULL (auto resolves to latest FY cache)
  out_db <- tempfile(fileext = ".sqlite")
  on.exit(unlink(out_db, force = TRUE), add = TRUE)

  res <- createSSURGO(filename = out_db, exdir = NULL, quiet = TRUE)
  expect_true(length(res) > 0)

  con <- DBI::dbConnect(RSQLite::SQLite(), out_db)
  on.exit(try(DBI::dbDisconnect(con), silent = TRUE), add = TRUE)

  # Check that legend, mapunit, or spatial tables contain data from both SSAs
  if (DBI::dbExistsTable(con, "legend")) {
    leg <- DBI::dbReadTable(con, "legend")
    expect_true(all(c("MH936", "FL616") %in% leg$areasymbol))
  }

  if (DBI::dbExistsTable(con, "mupolygon")) {
    mupolygon <- sf::st_read(out_db, "mupolygon", quiet = TRUE)
    expect_true(nrow(mupolygon) > 0)
    expect_true(all(c("MH936", "FL616") %in% unique(mupolygon$areasymbol)))
  }

  # Test filtering with areasymbols argument
  out_db_filtered <- tempfile(fileext = ".sqlite")
  on.exit(unlink(out_db_filtered, force = TRUE), add = TRUE)

  createSSURGO(filename = out_db_filtered, exdir = NULL, areasymbols = "MH936", quiet = TRUE)

  con_f <- DBI::dbConnect(RSQLite::SQLite(), out_db_filtered)
  on.exit(try(DBI::dbDisconnect(con_f), silent = TRUE), add = TRUE)

  if (DBI::dbExistsTable(con_f, "legend")) {
    leg_f <- DBI::dbReadTable(con_f, "legend")
    expect_true("MH936" %in% leg_f$areasymbol)
    expect_false("FL616" %in% leg_f$areasymbol)
  }
})

Try the soilDB package in your browser

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

soilDB documentation built on Nov. 26, 2026, 5:08 p.m.