Call the function functionName with the arguments contained in testdata and compare the results with the results in testdata for identity.

test_function(
  functionName,
  testdata = loadArgs(functionName, file.path(tempdir(), "test")),
  dbg = TRUE
)

Arguments

functionName

Name of the function to test. It must be callable, i.e. either defined in the global environment or on the search path.

testdata

List of lists containing function arguments (in elemenet args) and results (in element result), just as returned by loadArgs. If no testdata are given, it is tried to load test data by calling loadArgs on functionName.

dbg

if TRUE (default) debug messages are shown

Value

TRUE If the function functionName is able to reproduce the same results as given in the result elements in testdata

for all the argument combinations given in the args elements in

testdata.

Examples

# Define a function using saveArgs() to save arguments and result
squareSum <- function(a, b) {
  result <- a * a + b * b
  saveArgs("squareSum", args = list(a = a, b = b), result = result)
  result
}

# Set global variable TESTMODE to "activate" saveArgs() in squareSum()
TESTMODE <- TRUE

# Call the function with different arguments
squareSum(1, 2)
#> [Set global variable TESTMODE to FALSE to prevent this message]
#> Save args to 'squareSum' (y, n)? 
#> [1] 5
squareSum(2, 3)
#> [Set global variable TESTMODE to FALSE to prevent this message]
#> Save args to 'squareSum' (y, n)? 
#> [1] 13
squareSum(-1, -2)
#> [Set global variable TESTMODE to FALSE to prevent this message]
#> Save args to 'squareSum' (y, n)? 
#> [1] 5

# The arguments and function results were saved here:
dir(file.path(tempdir(), "test"))
#> character(0)

# Write a new (wrong) version of the function
squareSum.new <- function(a, b) {
  a * a - b * b
}

# Check if it returns the same results
test_function("squareSum.new", loadArgs("squareSum"))
#> Registered S3 method overwritten by 'compare':
#>   method           from    
#>   print.comparison testthat
#> Error: No such file: 'test' in
#>   '/var/folders/c9/jqpw9nhs7jj7vm5185nyw05h0000gn/T//RtmprftjbG'.
#> Available files:
#>   'downlit'
#>   'file13435c749744'
#>   'file134361d2d374'
#>   'file134376e6f487'

# If no test data are given, loadArgs is called on the function to test,
# i.e. testing squareSum on the test data created by the same function will
# return TRUE if the function did not change in the meanwhile.
test_function("squareSum")
#> Error: No such file: 'test' in
#>   '/var/folders/c9/jqpw9nhs7jj7vm5185nyw05h0000gn/T//RtmprftjbG'.
#> Available files:
#>   'downlit'
#>   'file13435c749744'
#>   'file134361d2d374'
#>   'file134376e6f487'