tests/testthat/test-listw.R

test_that("listw function creates a valid spatial weights list", {


  # Create a dummy dataset for testing
  dummy_data <- data.frame(
    district_code = 1:10,
    mean_household_wealth = rnorm(10, 5, 1)
  )

  # Create dummy geometries for the shapefile simulation
  dummy_geometries <- sf::st_sfc(lapply(1:10, function(x) {
    sf::st_polygon(list(matrix(c(0, 0, 1, 0, 1, 1, 0, 1, 0, 0) + x, ncol = 2, byrow = TRUE)))
  }))

  # Simulate the shapefile data
  shapefile_simulated <- sf::st_sf(
    objectid = 1:10,
    geometry = dummy_geometries
  )

  # Define the shapefile path (replace with an actual path if testing locally)
  shapefile_path <- "dummy_shapefile.shp"

  # Write the dummy shapefile to disk (only for local testing)
  sf::st_write(shapefile_simulated, shapefile_path)

  # Run the listw function
  result_listw <- listw(
    shapefile_path = shapefile_path,
    data = dummy_data,
    loc_shape = "objectid",
    loc_data = "district_code",
    weight_function = function(d) exp(-d / 0.2)
  )

  # Check that the result is a valid listw object
  expect_true(inherits(result_listw, "listw"))
  expect_s3_class(result_listw, "listw")

  # Clean up the shapefile (only for local testing)
  file.remove(shapefile_path)

  # Specify the path to the dummy shapefile without extension
  shapefile_base <- "dummy_shapefile"

  # List all related files (shapefile consists of multiple files like .shp, .shx, .dbf, etc.)
  files_to_delete <- list.files(pattern = paste0(shapefile_base, ".*"))

  # Delete the files
  unlink(files_to_delete)

})

Try the DHSr package in your browser

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

DHSr documentation built on April 4, 2025, 12:18 a.m.