tests/testthat/test-dict.R

context("dict")

test_that("simple set/get work", {
  d <- dict()

  d$set("x", 1)
  expect_equal(d$get("x"), 1)
  expect_equal(d$size(), 1)
  expect_equal(d$keys(), "x")
  expect_equal(length(d$items()), 1)
  expect_null(d$get("xx"))
  expect_equal(d$get("xx", default = "szymon"), "szymon")

  val <- "promise"
  delayedAssign("prom", val)
  d$set("p", prom)
  val <- "promise_changed"
  expect_equal(d$get("p"), "promise")

  expect_error(d$get(1L))
  expect_error(d$get(NA))
  expect_null(d$get(NA_character_))

  d$clear()
  expect_true(d$is_empty())
  expect_equal(length(d), 0)
})

test_that("dict correctly updated with another dict, removing", {
  d <- dict()
  other <- dict()

  d$set("x", 1)
  d$set("y", "szymon")
  it <- d$items()

  expect_equal(length(it), 2)

  keys <- c(it[[1]]$key, it[[2]]$key)
  expect_equal(sort(keys), c("x", "y"))

  values <- c(it[[1]]$value, it[[2]]$value)
  expect_equal(sort(values), c("1", "szymon"))

  other$set("y", "kub")
  other$set("new", list(seq(10)))

  d$update(other)

  expect_equal(d$get("x"), 1)
  expect_equal(d$get("y"), "kub")
  expect_equal(d$get("new"), list(seq(10)))
  expect_true(d$has_key("new"))

  d$delete("new")
  expect_false(d$has_key("new"))
  expect_error(d$has_key(quote(new)))
  expect_error(d$has_key(c("old", "new")))
  expect_error(d$has_key(1L))
  expect_null(d$get("new"))

  expect_warning(d$delete(c("x", "y", "z")))
  expect_true(d$is_empty())
  expect_true(d$size() == 0)
})

test_that("dict constructors behave as expected", {
  d_1arg <- dict(x = list(single = "list"))
  expect_equal(d_1arg[["x"]], list(single = "list"))

  d_2named <- dict(a = "x", b = "y")
  expect_equal(d_2named$keys(), c("a", "b"))
  expect_equal(d_2named$get("a"), "x")

  # corner-cases
  expect_is(dict(a = new.env())["a"], "list")
  expect_is(dict(a = new.env())[["a"]], "environment")
  expect_equal(dict(l = list())[["l"]], list())
  expect_equal(dict(nm = c())[["nm"]], c())
  expect_equal(dict(keys = 1)["keys"], list(keys = 1))
  expect_equal(dict(values = 2)[["values"]], 2)
  expect_error(dict(1))
  expect_error(dict("1"))
})
skubicius/dictionary documentation built on May 7, 2019, 7:17 p.m.