From 0d01a1eeb72656ed742ed9a636490d7c4eb56084 Mon Sep 17 00:00:00 2001 From: Sam Date: Tue, 19 Dec 2023 15:25:02 +0000 Subject: [PATCH] error check create_clean_reported_cases and add unit tests to cover function --- R/create.R | 6 +++- .../test-create_clean_reported_cases.R | 32 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 tests/testthat/test-create_clean_reported_cases.R diff --git a/R/create.R b/R/create.R index be09971f2..67a3e76ee 100644 --- a/R/create.R +++ b/R/create.R @@ -18,6 +18,8 @@ #' @author Sam Abbott #' @author Lloyd Chapman #' @export +#' @examples +#' create_clean_reported_cases(example_confirmed, 7) create_clean_reported_cases <- function(reported_cases, horizon, filter_leading_zeros = TRUE, zero_threshold = Inf) { @@ -38,7 +40,9 @@ create_clean_reported_cases <- function(reported_cases, horizon, reported_cases <- data.table::setorder(reported_cases, date) ## Filter out 0 reported cases from the beginning of the data if (filter_leading_zeros) { - reported_cases <- reported_cases[order(date)][min(date[confirm > 0])] + reported_cases <- reported_cases[order(date)][ + date >= min(date[confirm[!is.na(confirm)] > 0]) + ] } # Check case counts preceding zero case counts and set to 7 day average if diff --git a/tests/testthat/test-create_clean_reported_cases.R b/tests/testthat/test-create_clean_reported_cases.R new file mode 100644 index 000000000..132c1753c --- /dev/null +++ b/tests/testthat/test-create_clean_reported_cases.R @@ -0,0 +1,32 @@ + +test_that("create_clean_reported_cases runs without errors", { + expect_no_error(create_clean_reported_cases(example_confirmed, 7)) +}) + +test_that("create_clean_reported_cases returns a data table", { + result <- create_clean_reported_cases(example_confirmed, 7) + expect_s3_class(result, "data.table") +}) + +test_that("create_clean_reported_cases filters leading zeros correctly", { + # Modify example_confirmed to have leading zeros + modified_data <- example_confirmed + modified_data[1:3, "confirm"] <- 0 + + result <- create_clean_reported_cases(modified_data, 7) + # Check if the first row with non-zero cases is retained + expect_equal(result$date[1], min(modified_data$date[modified_data$confirm > 0])) +}) + +test_that("create_clean_reported_cases replaces zero cases correctly", { + # Modify example_confirmed to have zero cases that should be replaced + modified_data <- example_confirmed + modified_data$confirm[10:16] <- 0 + threshold <- 10 + + result <- create_clean_reported_cases( + modified_data, 0, zero_threshold = threshold + ) + # Check if zero cases within the threshold are replaced + expect_equal(sum(result$confirm == 0, na.rm = TRUE), 0) +})