tests/testthat/test-type_check.R

# Some fundamental tests that cover the standard cases of a type check.
test_that("Basic Type Check", {
  if (!requireNamespace("lubridate", quietly = TRUE)) {
    testthat::fail("Lubridate namespace required for this test.")
  }
  # Try to force Lubridate to load.
  expect_identical(lubridate::as_datetime(10), as.POSIXct(10, tz = "UTC"))
  template <- dplyr::tibble(
    "a" = character(0),
    "b" = numeric(0),
    "c" = integer(0),
    "d" = logical(0),
    "e" = list(),
    "f" = lubridate::POSIXct()
  )
  test_data_1 <- dplyr::tibble(
    "a" = 1,
    "b" = "2.5",
    "c" = 2.5,
    "d" = 1,
    "e" = NA,
    "f" = 0
  )
  test_data_2 <- dplyr::tibble(
    "a" = "",
    "b" = "",
    "g" = "",
    "h" = ""
  )
  key <- dplyr::tibble(
    "a" = "1",
    "b" = 2.5,
    "c" = 2L,
    "d" = TRUE,
    "e" = list(NA),
    "f" = as.POSIXct(0, tz = "UTC")
  )
  expect_identical(type_check(template, test_data_1, TRUE, NULL), key)
  expect_identical(type_check(template, key, TRUE, NULL), key)
  expect_identical(type_check(template, template, TRUE, NULL), template)
  # Output tests.
  output_test_1 <- capture.output(tmp <- type_check(template, test_data_2, FALSE, c("missing", "excess")))
  n <- nchar(output_test_1[[2]])
  m <- nchar(output_test_1[[3]])
  expect_identical(substr(output_test_1[[2]], n-9+1, n), ": c d e f")
  expect_identical(substr(output_test_1[[3]], m-5+1, m), ": g h")
  # Just ensure that we have functional debugging.
  expect_no_error(output_test_2 <- capture.output(
    type_check(template, test_data_2, FALSE, c("casts", "missing", "excess", "debug"))
  ))
})

test_that("Input Checking", {
  expect_error(type_check(NULL, iris))
  expect_error(type_check(iris, NULL))
  expect_error(type_check(c(1,2,3), c(4,5,6)))
})

test_that("Bad Dates", {
  template <- list("a" = as.POSIXct(NULL, tz = "UTC"))
  test_data <- list("a" = NA)
  expect_no_error(output_test <- capture.output(type_check(template, test_data, TRUE, "casts")))
})

Try the structenforcement package in your browser

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

structenforcement documentation built on June 8, 2025, 11:49 a.m.