# Helper to create a minimal valid R package for testing pkg tools local_minimal_package <- function( pkg_name = "testpkg", with_tests = TRUE, with_coverage = TRUE, .local_envir = parent.frame() ) { pkg_dir <- withr::local_tempdir(.local_envir = .local_envir) # Create package structure dir.create(file.path(pkg_dir, "R"), recursive = TRUE) if (with_tests) { dir.create(file.path(pkg_dir, "tests", "testthat"), recursive = TRUE) } dir.create(file.path(pkg_dir, "man"), recursive = TRUE) # Write minimal DESCRIPTION desc <- sprintf( "Package: %s Version: 0.1.0 Title: Test Package Description: A minimal package for testing. Authors@R: person(\"Test\", \"User\", email = \"test@example.com\", role = c(\"aut\", \"cre\")) License: MIT + file LICENSE Encoding: UTF-8 Roxygen: list(markdown = TRUE) RoxygenNote: 7.0.0 ", pkg_name ) writeLines(desc, file.path(pkg_dir, "DESCRIPTION")) # Write minimal NAMESPACE writeLines("# Generated by roxygen2: do not edit by hand", file.path(pkg_dir, "NAMESPACE")) # Always write at least a simple R function for valid package structure if (with_coverage) { r_code <- "# Example function #' Add two numbers #' #' @param x A number #' @param y A number #' @return The sum of x and y #' @export add_numbers <- function(x, y) { if (!is.numeric(x) || !is.numeric(y)) { stop(\"Both arguments must be numeric\") } x + y } #' Multiply two numbers (uncovered) #' #' @param x A number #' @param y A number #' @return The product of x and y #' @export multiply_numbers <- function(x, y) { if (!is.numeric(x) || !is.numeric(y)) { stop(\"Both arguments must be numeric\") } x * y } " writeLines(r_code, file.path(pkg_dir, "R", "example.R")) # Write corresponding test (only tests add_numbers, not multiply_numbers) if (with_tests) { test_code <- "test_that(\"add_numbers works\", { expect_equal(add_numbers(1, 2), 3) expect_equal(add_numbers(0, 0), 0) expect_equal(add_numbers(-1, 1), 0) }) test_that(\"add_numbers validates input\", { expect_error(add_numbers(\"a\", 2), \"must be numeric\") expect_error(add_numbers(1, \"b\"), \"must be numeric\") }) " writeLines(test_code, file.path(pkg_dir, "tests", "testthat", "test-example.R")) # Write testthat.R helper testthat_helper <- sprintf( "library(testthat) library(%s) test_check(\"%s\") ", pkg_name, pkg_name ) writeLines(testthat_helper, file.path(pkg_dir, "tests", "testthat.R")) } } else { # Even without coverage tests, need a minimal R file for valid package r_code <- "# Minimal package content #' A simple constant #' @export pkg_version <- \"0.1.0\" " writeLines(r_code, file.path(pkg_dir, "R", "constants.R")) } invisible(pkg_dir) }