library(testthat)

test_that("index of mome", {

mod <-
"
m ~ x + w + x:w
y ~ m
"

mod_es <- c("m ~ x" = "n",
            "y ~ x" = "m",
            "m ~ w" = "n",
            "m ~ x:w" = "l")

sim_only <- power4test(nrep = 5,
                       model = mod,
                       pop_es = mod_es,
                       n = 100,
                       R = 100,
                       do_the_test = FALSE,
                       progress = !is_testing(),
                       parallel = FALSE,
                       iseed = 1234)

test_out1 <- power4test(object = sim_only,
                         test_fun = test_index_of_mome,
                         test_args = list(x = "x",
                                          m = "m",
                                          y = "y",
                                          w = "w",
                                          mc_ci = TRUE))

(chk <- test_summary(test_out1))


test_out1b <- power4test(object = sim_only,
                         test_fun = test_index_of_mome,
                         test_args = list(x = "x",
                                          m = "m",
                                          y = "y",
                                          w = "w",
                                          mc_ci = TRUE,
                                          test_method = "pvalue"))

(chkb <- test_summary(test_out1b))
expect_equal(chk[[1]]["sig"],
             chkb[[1]]["sig"])

fits <- lapply(sim_only$sim_all,
               function(x) x$extra$fit)
mc_outs <- lapply(sim_only$sim_all,
                  function(x) x$extra$mc_out)
chk_outs <- mapply(manymome::index_of_mome,
                   fit = fits,
                   mc_out = mc_outs,
                   MoreArgs = list(x = "x",
                                   m = "m",
                                   y = "y",
                                   w = "w",
                                   mc_ci = TRUE),
                  SIMPLIFY = FALSE)
chk_cis <- lapply(chk_outs,
                  confint)
chk_cis <- do.call(rbind, chk_cis)
chk_sigs <- (chk_cis[, 1] > 0) | (chk_cis[, 2] < 0)

expect_equal(chk[[1]]["sig"],
             mean(chk_sigs),
             ignore_attr = TRUE)
expect_equal(chk[[1]][c("cilo", "cihi")],
             colMeans(chk_cis),
             ignore_attr = TRUE)

expect_no_error(capture.output(print(test_out1)))

})
