tests/testthat/test-nest.R

test_that("it validates argument `levels`", {
    expect_type(nest(1L), "list")
    expect_type(nest(""), "list")
    expect_error(nest(TRUE))
    expect_error(nest(-1L))
    expect_error(nest(NA_integer_))
    expect_snapshot(nest(-1L),         error = TRUE)
    expect_snapshot(nest(NA_integer_), error = TRUE)
})

test_that("it silently coerces `levels` if it is a double", {
    expect_identical(nest(2.0), list(list(NULL)))
})

test_that("it returns a list with the desired number of levels if `levels` is an integer", {
    expect_identical(nest(0L), NULL)
    expect_identical(nest(1L), list(NULL))
    expect_identical(nest(2L), list(list(NULL)))
    expect_identical(nest(3L), list(list(list(NULL))))
})

test_that("it returns a list with the desired number of levels if `levels` is a character", {
    # When passing character(N) to `levels`, elements
    # of that character vector are all equal to "",
    # not NULL. These empty names are then passed to
    # their underlying levels. Internally, empty names
    # are technically NOT equivalent to NULL `names`
    # (NULL `names` attribute).

    level0 <- NULL
    level1 <- structure(list(level0), names = "")
    level2 <- structure(list(level1), names = "")
    level3 <- structure(list(level2), names = "")

    expect_identical(nest(character(0L)), NULL)
    expect_identical(nest(character(1L)), level1)
    expect_identical(nest(character(2L)), level2)
    expect_identical(nest(character(3L)), level3)
})

test_that("it returns named lists if `levels` is a character of non-empty strings", {
    expect_identical(
        nest("terminal_node"),
        list(terminal_node = NULL))
    expect_identical(
        nest(c("level1", "terminal_node")),
        list(level1 = list(terminal_node = NULL)))
    expect_identical(
        nest(c("level1", "level2", "terminal_node")),
        list(level1 = list(level2 = list(terminal_node = NULL))))
})

test_that("it nests any value passed to `value`", {
    expect_identical(nest(1L, "nested value"),     list("nested value"))
    expect_identical(nest("node", "nested value"), list(node = "nested value"))
})
jeanmathieupotvin/dotprofile documentation built on Dec. 20, 2021, 10:08 p.m.