test_that("blockMatch returns m and all with expected columns", { set.seed(42) n <- 40L dat <- data.frame(x = rnorm(n), w = rnorm(n), z = rep(0:1, each = n / 2L)) pr <- runif(n) prG <- 2L dat$prc <- as.integer(cut(pr, stats::quantile(pr, (0:prG) / prG), include.lowest = TRUE)) bd <- basicDistance(dat) out <- suppressWarnings( blockMatch(dat, cost = bd$cost, J = 2L, ratio = 1L, rseed = 42L) ) expect_type(out, "list") expect_named(out, c("m", "all")) expect_s3_class(out$m, "data.frame") expect_s3_class(out$all, "data.frame") expect_true("matched" %in% names(out$all)) expect_true(all(c("mset", "z") %in% names(out$m))) J <- 2L expect_true(all(table(out$m$mset) == J)) expect_equal(sum(out$all$matched), nrow(out$m)) xm <- out$m by_mset <- split(seq_len(nrow(xm)), xm$mset) diffs <- vapply(by_mset, function(rows) { zi <- xm$z[rows] xi <- xm$x[rows] mean(xi[zi == 1]) - mean(xi[zi == 0]) }, numeric(1)) expect_true(all(is.finite(diffs))) }) test_that("blockMatch requires ratio >= J - 1", { dat <- data.frame(x = 1:4, z = c(1, 1, 0, 0), prc = rep(1L, 4)) bd <- basicDistance(dat) expect_error( blockMatch( dat, cost = bd$cost, J = 4L, ratio = 1L ) ) }) test_that("blockMatch warns when no stratum has both arms", { dat <- data.frame(x = rnorm(4), z = c(1, 1, 0, 0), prc = c(1L, 1L, 2L, 2L)) bd <- basicDistance(dat) expect_warning( out <- blockMatch(dat, cost = bd$cost, J = 2L, ratio = 1L, rseed = 1L), "no matched sets" ) expect_null(out$m) expect_false(any(out$all$matched)) }) test_that("blockMatch requires z and prc columns in dat", { dat <- data.frame(x = 1:4, prc = rep(1L, 4)) bd <- basicDistance(data.frame(x = 1:4, z = c(1, 1, 0, 0), prc = rep(1L, 4))) expect_error( blockMatch(dat, cost = bd$cost, J = 2L, ratio = 1L), "z must be a column" ) }) test_that("blockMatch runs with multiple strata that each support matching", { set.seed(1) n <- 24L dat <- data.frame(x = rnorm(n), z = c(rep(1L, 6L), rep(0L, 6L), rep(1L, 6L), rep(0L, 6L)), prc = c(rep(1L, 12L), rep(2L, 12L))) bd <- basicDistance(dat) out <- suppressWarnings( blockMatch(dat, cost = bd$cost, J = 2L, ratio = 1L, rseed = 1L) ) expect_s3_class(out$m, "data.frame") expect_true(length(unique(out$all$prc[out$all$matched])) <= 2L) })