knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  eval = FALSE
)

Some exercises require a student to hand-craft a function to make their code DRY. With check_fun_def() and a range of related helper check_ functions you can check the correctness of these user-defined functions.

As an example, have a look at the following solution:

# Define my_fun
my_fun <- function(a, b) {
  abs(a) + abs(b)
}

The following SCT checks the function definition and whether the function was properly called:

ex() %>% check_fun_def("my_fun") %>% {
  check_arguments(.)
  check_call(., 1, 2) %>% check_result() %>% check_equal()
  check_call(., -1, 2) %>% check_result() %>% check_equal()
  check_call(., 1, -2) %>% check_result() %>% check_equal()
  check_call(., -1, -2) %>% check_result() %>% check_equal()
  check_body(.) %>% {
    check_function(., "abs", index = 1)
    check_function(., "abs", index = 2)
  }
}

Note: in addition to check_result(), you can also pipe the result of check_call() into check_output() and check_error(), and follow up with check_equal(). These functions will respectively check the output and error the function call generated when executed in the student/solution environment.



Data-Camp/testwhat documentation built on June 24, 2022, 9:59 p.m.