From a50331e6547f87cee4558a0fd622d8da885afdf3 Mon Sep 17 00:00:00 2001
From: David Dorchies <david.dorchies@inrae.fr>
Date: Tue, 27 Feb 2024 17:22:01 +0100
Subject: [PATCH] fix(add_report): check if template exists

Refs #11
---
 R/add_report.R                   | 7 +++++--
 man/add_report.Rd                | 2 +-
 tests/testthat/test-add_report.R | 9 +++++++++
 3 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/R/add_report.R b/R/add_report.R
index 0593c77..7db8e28 100644
--- a/R/add_report.R
+++ b/R/add_report.R
@@ -10,10 +10,13 @@
 #'
 #' @inherit create_reports examples
 #'
-add_report <- function(name, template = "inrae", path = ".") {
-  if (!dir.exists(file.path(path, "reports"))) {
+add_report <- function(name, template = "inrae", path = pkgload::pkg_path()) {
+  if (!all(dir.exists(file.path(path, c("reports", "templates"))))) {
     stop("Report structure not found, call `create_reports` first!")
   }
+  if (!dir.exists(file.path(path, "templates", template))) {
+    stop("Template\"", template, "\" not found in ", file.path(path, "templates"))
+  }
   destpath <- file.path(path, "reports", name)
   if (dir.exists(destpath))
     stop("The folder ",
diff --git a/man/add_report.Rd b/man/add_report.Rd
index be5f79a..29b1dbe 100644
--- a/man/add_report.Rd
+++ b/man/add_report.Rd
@@ -4,7 +4,7 @@
 \alias{add_report}
 \title{Add a new report in a fairify project}
 \usage{
-add_report(name, template = "inrae", path = ".")
+add_report(name, template = "inrae", path = pkgload::pkg_path())
 }
 \arguments{
 \item{name}{Name of the report (sub-folder name in "reports")}
diff --git a/tests/testthat/test-add_report.R b/tests/testthat/test-add_report.R
index e487ea7..3396919 100644
--- a/tests/testthat/test-add_report.R
+++ b/tests/testthat/test-add_report.R
@@ -2,6 +2,15 @@ test_that("add_report should raise error if reports does not exists", {
   path <- tempfile(pattern = "dir")
   dir.create(path, recursive = TRUE)
   expect_error(add_report("test", path = path))
+  unlink(path, recursive = TRUE)
+})
+
+test_that("add_report should raise error if template does not exists", {
+  path <- tempfile(pattern = "dir")
+  dir.create(path, recursive = TRUE)
+  create_reports(path)
+  expect_error(add_report("test", template = "wrong_template", path = path))
+  unlink(path, recursive = TRUE)
 })
 
 test_that("add_report should create a report", {
-- 
GitLab