Skip to content

Commit

Permalink
test(census_geo_api): add test that age/sex subsets sum to race totals
Browse files Browse the repository at this point in the history
  • Loading branch information
rossellhayes committed Apr 2, 2024
1 parent 76953c2 commit 0d3c08d
Showing 1 changed file with 48 additions and 1 deletion.
49 changes: 48 additions & 1 deletion tests/testthat/test-census_geo_api.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ skip_if_not(nzchar(Sys.getenv("CENSUS_API_KEY")))

test_that("snapshot", {
# TODO: Test that sub-geographies sum to match pooled geographies (e.g. blocks sum to block groups, sum to tracts, sum to counties)
# TODO: Test that age/sex subsets sum to race totals

# These snapshots were generated using the calculations in v2.0.0
# and verified that the calculations resulted in the same numbers for PR #120.
Expand All @@ -23,3 +22,51 @@ test_that("snapshot", {
style = "deparse"
)
})

expect_subset_sums_equal_overall_total <- function(data) {
`%>%` <- dplyr::`%>%`

sums <- data %>%
dplyr::select(-dplyr::starts_with("r_")) %>%
tidyr::pivot_longer(dplyr::starts_with("P")) %>%
dplyr::mutate(
subset = dplyr::case_when(
grepl("001", name) ~ "overall",
.default = "subset"
),
name = sub("_.+", "", name)
) %>%
dplyr::summarise(
value = sum(value),
.by = -value
) %>%
dplyr::summarize(
are_equal = length(unique(value)) <= 1,
.by = c(-subset, -value)
)

expect_true(all(sums$are_equal))
}

test_that("sums", {
expect_subset_sums_equal_overall_total(
census_geo_api(state = "DE", geo = "county", year = "2020", sex = TRUE)
)
expect_subset_sums_equal_overall_total(
census_geo_api(state = "DE", geo = "county", year = "2020", age = TRUE)
)
expect_subset_sums_equal_overall_total(
census_geo_api(state = "DE", geo = "county", year = "2020", age = TRUE, sex = TRUE)
)
expect_subset_sums_equal_overall_total(
census_geo_api(state = "DE", geo = "county", year = "2010", sex = TRUE)
)
expect_subset_sums_equal_overall_total(
census_geo_api(state = "DE", geo = "county", year = "2010", age = TRUE)
)
expect_subset_sums_equal_overall_total(
census_geo_api(state = "DE", geo = "county", year = "2010", age = TRUE, sex = TRUE)
)
})

# TODO: Test that all variables sum to total population of geography

0 comments on commit 0d3c08d

Please sign in to comment.