tests/testthat/test-utils.R

test_that("term matching works correctly", {

	# Create list of formulas to test term matchign
	t <- rx(mpg + wt ~ hp + am + vs + cyl)
	f <- deparse1(stats::formula(t)) # Trace/pare
	fl <- fmls(t, order = 1:4, pattern = "fundamental") # Unit level paths
	tl <- rx()

	for (i in seq_along(fl)) {
		tl <- append(tl, match_runes(t, lhs(fl[i])))
	}

	expect_length(unique(tl), 2)
})


test_that("list manipulation occurs for formulas, tables, and named lists", {

	# Named lists of different varieties
  label <- list(mpg ~ "Mileage", hp ~ Horsepower)
  tier <- list("qsec" ~ "speed", wt ~ "hardware")
  role <- list(cyl + gear ~ "confounder")

  # Convert to formulas
  expect_named(formula_to_named_list(label), c("mpg", "hp"))
  expect_named(formula_to_named_list(tier), c("qsec", "wt"))
  expect_named(formula_to_named_list(role), c("cyl", "gear"))

  # More complex classes
  nums <- list(limits ~ c(0, 1))
  expect_named(formula_to_named_list(nums), "limits")
  expect_error(formula_to_named_list(list(limits = c(0, 1))))

  # Additional testing for numeric values
  x <- list(int ~ 1)
  expect_named(formula_to_named_list(x), "int")
  expect_equal(formula_to_named_list(x)$int, 1)

  # Convert back to named list
  x <- formula_to_named_list(role)
  y <- named_list_to_formula(x)
  expect_length(y, 2)
  expect_equal(y[[1]], cyl ~ "confounder", ignore_attr = TRUE)


})

test_that("sides can be obtained from formulaic objects", {

	x <- sx(mpg + wt ~ X(hp) + M(cyl) + qsec)
	fl <-
		fmls(x, order = 1:4) |>
		{
			\(.x) .x[field(.x, "n") == 2]
		}()
	# Number 5 doesn't have a "left" hand side, which is wrong.
	f <- fl[2]
	expect_equal(lhs(f), "cyl")

})


test_that("labels can be extracted from objects", {

	t1 <- distill_rune(mpg ~ wt + hp + gear, label = list(mpg ~ "Mileage"))
	t2 <- distill_rune(am ~ wt + hp + gear, label = list(am ~ "Automatic Transmission"))
	t3 <- distill_rune(cyl ~ wt + hp + gear, label = list(cyl ~ "Cylinders"))
	# For checking duplicate labels
	t4 <- distill_rune(cyl ~ wt + hp + gear, label = list(cyl ~ "Cycles"))
	x <- list(t1, t2, t3)
	three <- rune_list(x)

	# Get labels from runes and rune lists
	labs <- labels(three)
	expect_length(labs, 3)
	expect_named(labs, c("mpg", "am", "cyl"))

	# If duplicates should message
	four <- rune_list(list(t1, t2, t3, t4))
	expect_message(labels(four))

})
asshah4/rx documentation built on Nov. 8, 2022, 3:09 p.m.