diff --git a/R/spending.R b/R/spending.R index 6132224..8830fe9 100644 --- a/R/spending.R +++ b/R/spending.R @@ -185,10 +185,28 @@ cog_spending <- function(govid, years, category = NULL, #' @noRd .notes_column <- function(result) { - if (nrow(result) == 0L) return(character(0)) - ifelse( - isTRUE(result$aggregate_fallback) | result$aggregate_fallback %in% TRUE, + n <- nrow(result) + if (n == 0L) return(character(0)) + parts <- vector("list", 2L) + agg <- result[["aggregate_fallback"]] + parts[[1]] <- ifelse( + !is.null(agg) & isTRUE(any(agg, na.rm = TRUE)) & agg %in% TRUE, "Aggregate fallback applied; see cog_explain()", - "" + NA_character_ ) + ps <- result[["pop_source"]] + parts[[2]] <- if (!is.null(ps)) { + ifelse(ps == "unavailable", + "No population denominator available for this gov type", + NA_character_) + } else { + rep(NA_character_, n) + } + out <- character(n) + for (i in seq_len(n)) { + pieces <- vapply(parts, `[[`, character(1), i) + pieces <- pieces[!is.na(pieces)] + out[i] <- if (length(pieces) == 0L) "" else paste(pieces, collapse = "; ") + } + out } diff --git a/tests/testthat/test-spending.R b/tests/testthat/test-spending.R index d904b92..8c70a33 100644 --- a/tests/testthat/test-spending.R +++ b/tests/testthat/test-spending.R @@ -148,3 +148,28 @@ test_that("per_capita denominator is the per-year F-33 population", { expect_false(all(abs(implied_pop - 1940907) < 1)) }) }) + +test_that("pop_source = 'census_f33' does not produce unavailable-pop note", { + skip_if_no_corpus() + with_fixture_corpus({ + r <- cog_spending("101006006", years = 2019L, + category = "Police", per_capita = TRUE) + expect_true(all(r$pop_source == "census_f33")) + expect_true(all(is.na(r$notes) | r$notes == "" | + !grepl("No population denominator", r$notes))) + }) +}) + +test_that("aggregate fallback + unavailable pop produce concatenated notes", { + # Unit-level test of .notes_column with a synthetic data frame so we don't + # depend on having a type-4/5 gov in the fixture. + result <- tibble::tibble( + aggregate_fallback = c(FALSE, TRUE, TRUE), + pop_source = c("census_f33", "census_f33", "unavailable") + ) + notes <- uscogdata:::.notes_column(result) + expect_equal(notes[1], "") + expect_equal(notes[2], "Aggregate fallback applied; see cog_explain()") + expect_equal(notes[3], + "Aggregate fallback applied; see cog_explain(); No population denominator available for this gov type") +})