Use expect_custom to allow inclusion of arbitrary data in expectation results. Additional data is stored in a list in an attribute called custom in the resulting expectation. This allows data expectations to store information about the number of failed and successful cases for reporting of test results.

expect_custom(
  ok,
  failure_message,
  info = NULL,
  srcref = NULL,
  trace = NULL,
  ...
)

Arguments

ok

TRUE or FALSE indicating if the expectation was successful.

failure_message

Message to show if the expectation failed.

info

Character vector continuing additional information. Included for backward compatibility only and new expectations should not use it.

srcref

Location of the failure. Should only needed to be explicitly supplied when you need to forward a srcref captured elsewhere.

...

Additional data to be added to a list in the custom attribute of the resulting expectation.

Value

An expectation object. Signals the expectation condition with a continue_test restart.

Examples

# calling expect_custom directly with some custom data
x <- expect_custom(TRUE, "Test", extra_data = 1:5, more_data = "Hello")
str(x)
#> List of 4
#>  $ message: chr "Test"
#>  $ srcref : NULL
#>  $ trace  : NULL
#>  $ custom :List of 2
#>   ..$ extra_data: int [1:5] 1 2 3 4 5
#>   ..$ more_data : chr "Hello"
#>  - attr(*, "class")= chr [1:3] "expectation_success" "expectation" "condition"

# an example expectation (note additional libraries used)
library(rlang)
#> 
#> Attaching package: ‘rlang’
#> The following objects are masked from ‘package:testthat’:
#> 
#>     is_false, is_null, is_true

expect_example <- function(var, data = get_testdata()) {
  act <- quasi_label(enquo(data))
  act$var_desc <- expr_label(get_expr(enquo(var)))
  act$var <- expr_text(get_expr(enquo(var)))

  act$result <- act$val[[act$var]] > 0
  act$result[is.na(act$result)] <- FALSE

  expect_custom(
    all(act$result, na.rm = TRUE),
    glue::glue("{act$lab} has {sum(!act$result, na.rm = TRUE)} cases with \\
                {act$var_desc} not greater than 0."),
    failed_count = sum(!act$result, na.rm = TRUE),
    total_count = sum(!is.na(act$result))
  )

  invisible(act$result)
}

try(expect_example(x, data = data.frame(x = c(NA, -2:2))))
#> Error : data.frame(x = c(NA, -2:2)) has 4 cases with `x` not greater than 0.