tests/testthat/test-joining.R

test_that("Simple binding", {
  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" = ""
  )
  test_data_3 <- dplyr::tibble(
    "b" = 1,
    "c" = 2,
    "d" = 3
  )
  # Assure ourselves that the input DFs won't join.
  expect_error(dplyr::bind_rows(test_data_1, test_data_2), class = "vctrs_error_incompatible_type")
  # Then test some good cases.
  expect_identical(
    bind_as_struct(template, test_data_1, test_data_2, test_data_3), dplyr::tibble(
      "a" = c("1", "", NA_character_),
      "b" = c(2.5, NA_real_, 1),
      "c" = c(2L, NA_integer_, 2L),
      "d" = c(TRUE, NA, TRUE),
      "e" = list(NA, NULL, NULL),
      "f" = c(as.POSIXct(0, tz = "UTC"), NA, NA),
      "g" = c(NA_character_, "", NA_character_),
      "h" = c(NA_character_, "", NA_character_)
    )
  )
  expect_identical(
    bind_as_struct(template, test_data_2, test_data_3), dplyr::tibble(
      "a" = c("", NA_character_),
      "b" = c(NA_real_, 1),
      "g" = c("", NA_character_),
      "h" = c("", NA_character_),
      "c" = c(NA_integer_, 2L),
      "d" = c(NA, TRUE)
    )
  )
  expect_identical(
    bind_as_struct(template, test_data_2, test_data_3, strict = TRUE), dplyr::tibble(
      "a" = c("", NA_character_),
      "b" = c(NA_real_, 1),
      "c" = c(NA_integer_, 2L),
      "d" = c(NA, TRUE),
      "e" = list(NULL, NULL),
      "f" = as.POSIXct(c(NA, NA), tz = "UTC")
    )
  )
})

test_that("Bad Inputs", {
  expect_error(bind_as_struct(NULL, iris))
})

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.