R/stub.tests.R

Defines functions stub.tests

Documented in stub.tests

#' Generate unit tests for your helper functions.
#'
#' This function will parse all of the functions defined in files inside
#' of the \code{lib} directory and will generate a trivial unit test for
#' each function. The resulting tests are stored in the file
#' \code{tests/autogenerated.R}. Every test is excepted to fail by default,
#' so you should edit them before calling \code{\link{test.project}}.
#'
#' @return No value is returned; this function is called for its side effects.
#'
#' @export
#'
#' @examples
#' library('ProjectTemplate')
#'
#' \dontrun{stub.tests()}
stub.tests <- function()
{

  .stopifnotproject("Change to a valid ProjectTemplate directory and run stub.tests() again.")
  generate.arguments <- function(fun.name, tmp.env)
  {
    arguments <- names(formals(get(fun.name, envir = tmp.env, inherits = FALSE)))
    return(paste(sapply(arguments, function (argument) {paste(argument, '= NULL')}), collapse = ', '))
  }

  generate.test <- function(fun.name, tmp.env)
  {
    paste('expect_that(', fun.name, '(', generate.arguments(fun.name, tmp.env), '), equals(NULL))', sep = '')
  }

  unlink(file.path('tests', 'autogenerated.R'))

  # Source each file in the `lib` directory in a temporary environment.
  lib.files <- dir('lib', pattern = "[.][rR]$")
  tmp.env <- new.env()

  message(paste('Generating stub tests in ', file.path('tests', 'autogenerated.R'), ':', sep = ''))

  for (lib.file in lib.files)
  {
    sys.source(file.path('lib', lib.file), envir = tmp.env)

    # Create a test for each function created by those files.
    for (symbol in ls(tmp.env))
    {
      if (is(get(symbol, envir = tmp.env, inherits = FALSE),'function'))
      {
        cat(generate.test(symbol, tmp.env),
            file = file.path('tests', 'autogenerated.R'),
            append = TRUE)
        cat('\n',
            file = file.path('tests', 'autogenerated.R'),
            append = TRUE)
        message(paste(' ', symbol, sep = ''))
      }
    }
  }
}

Try the ProjectTemplate package in your browser

Any scripts or data that you put into this service are public.

ProjectTemplate documentation built on July 4, 2024, 1:10 a.m.