tests/testthat/test-context.R

test_that("cur_group() works", {
  df <- tibble(g = 1, x = 1)
  gf <- group_by(df, g)

  expect_equal(
    df %>% summarise(key = list(cur_group())) %>% pull(key),
    list(tibble(.rows = 1L))
  )
  expect_equal(
    gf %>% summarise(key = list(cur_group())) %>% pull(key),
    list(tibble(g = 1))
  )

})

test_that("cur_group_idx() gives unique id", {
  df <- tibble(x = c("b", "a", "b"))
  gf <- group_by(df, x)

  expect_equal(
    summarise(gf, id = cur_group_id()),
    tibble(x = c("a", "b"), id = 1:2)
  )
  expect_equal(
    mutate(gf, id = cur_group_id()),
    group_by(tibble(x = df$x, id = c(2, 1, 2)), x)
  )
})


test_that("cur_data() gives current data without groups, cur_data_all() includes groups", {
  df <- tibble(x = c("b", "a", "b"), y = 1:3)
  gf <- group_by(df, x)

  expect_equal(
    df %>% summarise(x = list(cur_data())) %>% pull(),
    list(df)
  )

  expect_equal(
    gf %>% summarise(x = list(cur_data())) %>% pull(),
    list(tibble(y = 2L), tibble(y = c(1L, 3L)))
  )
  expect_equal(
    gf %>% summarise(x = list(cur_data_all())) %>% pull(),
    list(tibble(x = "a", y = 2L), tibble(x = "b", y = c(1L, 3L)))
  )
})

test_that("cur_group_rows() retrieves row position in original data", {
  df <- tibble(x = c("b", "a", "b"), y = 1:3)
  gf <- group_by(df, x)

  expect_equal(
    df %>% summarise(x = list(cur_group_rows())) %>% pull(),
    list(1:3)
  )

  expect_equal(
    gf %>% summarise(x = list(cur_group_rows())) %>% pull(),
    list(2L, c(1L, 3L))
  )
})

test_that("cur_data() and cur_data_all() work sequentially", {
  df <- tibble(a = 1)
  expect_equal(
    mutate(df, x = ncol(cur_data()), y = ncol(cur_data())),
    tibble(a = 1, x = 1, y = 2)
  )

  gf <- tibble(a = 1, b = 2) %>% group_by(a)
  expect_equal(
    mutate(gf, x = ncol(cur_data_all()), y = ncol(cur_data_all())),
    group_by(tibble(a = 1, b = 2, x = 2, y = 3), a)
  )
})

test_that("give useful error messages when not applicable", {
  expect_snapshot(error = TRUE, n())

  expect_snapshot(error = TRUE, cur_data())
  expect_snapshot(error = TRUE, cur_data_all())

  expect_snapshot(error = TRUE, cur_column())
  expect_snapshot(error = TRUE, cur_group())
  expect_snapshot(error = TRUE, cur_group_id())
  expect_snapshot(error = TRUE, cur_group_rows())
})
javifar/TIDYVERSE-DPLYR documentation built on Dec. 20, 2021, 9:08 p.m.