Skip to content

Commit

Permalink
Improve error msg + increase test coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
olivroy committed Aug 12, 2024
1 parent 1c9da3c commit 807b484
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
5 changes: 3 additions & 2 deletions R/dplyr-plus.R
Original file line number Diff line number Diff line change
Expand Up @@ -156,12 +156,14 @@ slice_group_sample <- function(data, group_var = NULL, n_groups = 1) {
data <- dplyr::group_by(data, {{ group_var }})
}
if (!dplyr::is_grouped_df(data)) {
# nocov: start
cli::cli_abort(
c(
"Not supposed to happen"
),
.internal = TRUE
)
# nocov: end
}
# Assuming the data is grouped now.
group_var_name <- dplyr::group_vars(data)
Expand Down Expand Up @@ -353,8 +355,7 @@ extract_cell_value <- function(data, var, filter, name = NULL, length = NULL, un
if (!is.null(length) && !rlang::has_length(res2, length)) {
# TODO use `check_length()` when implemented. r-lib/rlang#1618
cli::cli_abort(c(
"Expected an output of {length}",
"Got an output of {length(res2)}"
"Expected an output of length {length}, not {length(res2)}."
))
}

Expand Down
8 changes: 8 additions & 0 deletions tests/testthat/_snaps/dplyr-plus.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,14 @@
2 1 344. 24.6
3 All vs 643. 20.1

# extract_cell_value() works

Code
extract_cell_value(dat, x >= 2, var = y, length = 1)
Condition
Error in `extract_cell_value()`:
! Expected an output of length 1, not 2.

# slice_min_max() works

Code
Expand Down
27 changes: 27 additions & 0 deletions tests/testthat/test-dplyr-plus.R
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,30 @@ test_that("summarise_with_total() keeps factors", {
expect_equal(levels(res$vs), c("Total", "0", "1"))
})

test_that("extract_cell_value() works", {
dat <- data.frame(
x = c(1, 2, 3),
y = c(1.5, 3, 3.5),
row.names = c("row1", "row2", "row4")
)
expect_equal(
extract_cell_value(
dat,
x == 2,
var = y
),
c("row2" = 3)
)
expect_snapshot(error = TRUE,
extract_cell_value(
dat,
x >= 2,
var = y,
length = 1
)
)
})

test_that("slice_min_max() works", {
expect_snapshot({
slice_min_max(mtcars, mpg, n = 3)
Expand All @@ -160,6 +184,9 @@ test_that("slice_min_max() works", {
nrow(slice_min_max(mtcars, mpg, with_ties = FALSE, n = 2, each = FALSE)),
2
)
expect_equal(
nrow(slice_min_max(mtcars, mpg, with_ties = FALSE)),
2)
})

test_that("na_if2() works with expr and values", {
Expand Down

0 comments on commit 807b484

Please sign in to comment.