Testing And Benchmarking in R Programming Language

Our first program will demonstrate unit testing and benchmarking in R. Here’s the full source code:

# Function to find the minimum of two integers
int_min <- function(a, b) {
  if (a < b) {
    return(a)
  }
  return(b)
}

# Basic test using testthat
library(testthat)

test_that("Basic int_min test", {
  ans <- int_min(2, -2)
  expect_equal(ans, -2, info = "int_min(2, -2) should return -2")
})

# Table-driven tests
test_that("Table-driven int_min tests", {
  tests <- list(
    list(a = 0, b = 1, want = 0),
    list(a = 1, b = 0, want = 0),
    list(a = 2, b = -2, want = -2),
    list(a = 0, b = -1, want = -1),
    list(a = -1, b = 0, want = -1)
  )
  
  for (tt in tests) {
    test_name <- sprintf("%d,%d", tt$a, tt$b)
    test_that(test_name, {
      ans <- int_min(tt$a, tt$b)
      expect_equal(ans, tt$want, info = sprintf("got %d, want %d", ans, tt$want))
    })
  }
})

# Benchmark using microbenchmark
library(microbenchmark)

benchmark_int_min <- microbenchmark(
  int_min(1, 2),
  times = 1000000
)

print(benchmark_int_min)

To run the tests and benchmarks, you can save this code in a file (e.g., int_min_test.R) and execute it using R:

$ Rscript int_min_test.R

This will run all the tests and display the results, including any failures. The benchmark results will also be displayed, showing the execution time statistics for the int_min function.

In R, we use the testthat package for unit testing. The test_that function is used to group related tests together. We use expect_equal to assert that the actual result matches the expected result.

For benchmarking, we use the microbenchmark package. This package provides more detailed timing information compared to simple timing methods.

Note that R doesn’t have a built-in concept of subtests like Go’s t.Run. Instead, we use separate test_that calls within a loop to achieve a similar effect for our table-driven tests.

The benchmark in R doesn’t use a loop with an increasing counter like in Go. Instead, the microbenchmark function handles running the code multiple times and collecting precise measurements.

This example demonstrates how to perform unit testing and benchmarking in R, providing similar functionality to the original example while using R-specific libraries and idioms.