tests/testthat/test-citations.R

library(apa7)
library(testthat)

test_that("apa7's BibTeX file is parsed into keys, authors, and years", {
  entries <- apa7:::bib_entries(apa7_bib())
  expect_true(all(c(
    "beggOperatingCharacteristicsRank1994",
    "cheungModelingDependentEffect2014",
    "duvalTrimFillSimple2000",
    "eggerBiasMetaanalysisDetected1997",
    "johnsonTestsCertainLinear1936"
  ) %in% names(entries)))
  expect_equal(entries$eggerBiasMetaanalysisDetected1997$authors[2], "Davey Smith")
  # Every entry has authors and a four-digit year (a malformed entry would not)
  expect_true(all(lengths(lapply(entries, `[[`, "authors")) > 0))
  expect_true(all(grepl("^([0-9]{4}/)?[0-9]{4}$", vapply(entries, `[[`, character(1), "year"))))
  chars <- strsplit(paste(readLines(apa7_bib()), collapse = ""), "")[[1]]
  expect_equal(sum(chars == "{"), sum(chars == "}"))
  expect_equal(apa7:::citation_text("cheungModelingDependentEffect2014"), "Cheung, 2014")
  expect_equal(apa7:::citation_text("duvalTrimFillSimple2000"), "Duval & Tweedie, 2000")
  expect_equal(apa7:::citation_text("duvalTrimFillSimple2000", narrative = TRUE), "Duval and Tweedie (2000)")
  expect_equal(apa7:::citation_text("eggerBiasMetaanalysisDetected1997"), "Egger et al., 1997")
  expect_equal(
    apa7:::citation_text("satorraScaledAdjustedRestricted2000", narrative = TRUE),
    "Satorra (2000)"
  )
  expect_equal(
    apa7:::citation_text("satorraScaledDifferenceChisquare2001", narrative = TRUE),
    "Satorra and Bentler (2001)"
  )
})

test_that("citation markers become text or keys", {
  s <- c(
    paste0("Method ", apa7:::cite("duvalTrimFillSimple2000"), " here."),
    paste0("As ", apa7:::cite("cheungModelingDependentEffect2014", narrative = TRUE), " showed."),
    "No citation."
  )
  expect_equal(
    apa7:::resolve_citations(s, "text"),
    c("Method (Duval & Tweedie, 2000) here.", "As Cheung (2014) showed.", "No citation.")
  )
  expect_equal(
    apa7:::resolve_citations(s, "keys"),
    c("Method [@duvalTrimFillSimple2000] here.", "As @cheungModelingDependentEffect2014 showed.", "No citation.")
  )
  # Outside a rendered document, auto gives text
  expect_equal(apa7:::resolve_citations(s, "auto"), apa7:::resolve_citations(s, "text"))
})

test_that("auto uses keys only for entries in the document's bibliography", {
  skip_if_not_installed("rmarkdown")
  dir <- withr::local_tempdir()
  bib <- file.path(dir, "refs.bib")
  writeLines(
    c("@article{duvalTrimFillSimple2000,", "  author = {Duval, Sue and Tweedie, Richard},", "  year = 2000", "}"),
    bib
  )
  withr::local_options(knitr.in.progress = TRUE)
  local_mocked_bindings(
    metadata = list(bibliography = bib),
    .package = "rmarkdown"
  )
  s <- c(
    paste0("A ", apa7:::cite("duvalTrimFillSimple2000"), "."),
    paste0("B ", apa7:::cite("cheungModelingDependentEffect2014"), ".")
  )
  expect_equal(
    apa7:::resolve_citations(s, "auto"),
    c("A [@duvalTrimFillSimple2000].", "B (Cheung, 2014).")
  )
})

test_that("a bibliography in Quarto directory or project metadata is found", {
  skip_if_not_installed("yaml")
  root <- withr::local_tempdir()
  sub <- file.path(root, "articles")
  dir.create(sub)
  writeLines("project:\n  type: default", file.path(root, "_quarto.yml"))
  writeLines("bibliography:\n  - ../refs.bib\n  - more.bib", file.path(sub, "_metadata.yml"))
  expect_equal(
    basename(apa7:::quarto_bib_files(sub)),
    c("refs.bib", "more.bib")
  )
  expect_true(all(startsWith(apa7:::quarto_bib_files(sub), normalizePath(sub, winslash = "/"))))
  # Project metadata applies when the folder sets no bibliography
  writeLines("project:\n  type: default\nbibliography: refs.bib", file.path(root, "_quarto.yml"))
  unlink(file.path(sub, "_metadata.yml"))
  expect_equal(basename(apa7:::quarto_bib_files(sub)), "refs.bib")
  # Directory metadata does not apply outside a Quarto project
  outside <- withr::local_tempdir()
  writeLines("bibliography: refs.bib", file.path(outside, "_metadata.yml"))
  expect_equal(apa7:::quarto_bib_files(outside), character(0))

  # auto resolves keys from the bibliography in directory metadata
  writeLines(
    c("@article{duvalTrimFillSimple2000,", "  author = {Duval, Sue and Tweedie, Richard},", "  year = 2000", "}"),
    file.path(root, "refs.bib")
  )
  withr::local_options(knitr.in.progress = TRUE)
  local_mocked_bindings(metadata = list(), .package = "rmarkdown")
  local_mocked_bindings(current_input = function(dir = FALSE) file.path(sub, "doc.qmd"), .package = "knitr")
  expect_equal(
    apa7:::resolve_citations(paste0("A ", apa7:::cite("duvalTrimFillSimple2000"), "."), "auto"),
    "A [@duvalTrimFillSimple2000]."
  )
})

test_that("several keys are cited together, all as keys or all as text", {
  s <- paste0("Method ", apa7:::cite(c("duvalTrimFillSimple2000", "cheungModelingDependentEffect2014")), ".")
  expect_equal(
    apa7:::resolve_citations(s, "text"),
    "Method (Duval & Tweedie, 2000; Cheung, 2014)."
  )
  expect_equal(
    apa7:::resolve_citations(s, "keys"),
    "Method [@duvalTrimFillSimple2000; @cheungModelingDependentEffect2014]."
  )
})

test_that("republished works are cited with the original and published years", {
  dir <- withr::local_tempdir()
  bib <- file.path(dir, "refs.bib")
  writeLines(
    c(
      "@incollection{tukeyProblem1994,", "  author = {Tukey, John W.},", "  year = 1994,", "  origdate = {1953}", "}",
      "@incollection{tukeyOther1994,", "  author = {Tukey, John W.},", "  date = {1994},", "  origyear = 1953", "}"
    ),
    bib
  )
  entries <- apa7:::bib_entries(bib)
  expect_equal(entries$tukeyProblem1994$year, "1953/1994")
  expect_equal(entries$tukeyOther1994$year, "1953/1994")
})

test_that("apa_note() takes citations as an argument or an option", {
  skip_if_not_installed("metafor")
  skip_if_not_installed("metadat")
  d <- metafor::escalc(
    measure = "RR",
    ai = tpos, bi = tneg, ci = cpos, di = cneg,
    data = metadat::dat.bcg
  )
  tbl <- apa_publication_bias(metafor::rma(yi, vi, data = d))
  expect_match(apa_note(tbl), "Trim and fill (Duval & Tweedie, 2000)", fixed = TRUE)
  expect_match(apa_note(tbl, citations = "keys"), "Trim and fill [@duvalTrimFillSimple2000]", fixed = TRUE)
  withr::local_options(apa7.citations = "keys")
  expect_match(apa_note(tbl), "[@beggOperatingCharacteristicsRank1994]", fixed = TRUE)
  expect_match(apa_note(tbl, citations = "text"), "(Begg & Mazumdar, 1994)", fixed = TRUE)
  expect_error(apa_note(tbl, citations = "bibtex"), "auto")
})

test_that("apa7_write_bib() writes the BibTeX file", {
  dir <- withr::local_tempdir()
  path <- file.path(dir, "apa7.bib")
  expect_equal(apa7_write_bib(path), path)
  expect_equal(readLines(path), readLines(apa7_bib()))
  expect_error(apa7_write_bib(path, overwrite = FALSE), "already exists")
  expect_error(apa7_write_bib(NA_character_), "file path")
})

test_that("every key cited in note code is in apa7's BibTeX file", {
  ns <- asNamespace("apa7")
  code <- unlist(lapply(ls(ns, all.names = TRUE), \(name) {
    f <- get(name, envir = ns)
    if (is.function(f)) deparse(f) else character(0)
  }))
  # Keys look like "authorTitleWords1999" (Better BibTeX), whether passed to
  # cite() directly or through switch()
  keys <- unique(unlist(regmatches(code, gregexpr('"[a-z]+[A-Z][A-Za-z]+[0-9]{4}"', code))))
  keys <- gsub('"', "", keys, fixed = TRUE)
  expect_gt(length(keys), 20)
  expect_true(all(keys %in% names(apa7:::bib_entries(apa7_bib()))), info = paste(setdiff(keys, names(apa7:::bib_entries(apa7_bib()))), collapse = ", "))
})

test_that("named procedures are cited as keys in keys mode", {
  skip_on_cran()
  fit <- lm(mpg ~ wt + factor(cyl), data = mtcars)
  expect_match(
    apa_note(apa_collinearity(fit), citations = "keys"),
    "generalized *VIF* [@foxGeneralizedCollinearityDiagnostics1992]",
    fixed = TRUE
  )
  g0 <- glm(am ~ wt, data = mtcars, family = binomial)
  g1 <- glm(am ~ wt + hp, data = mtcars, family = binomial)
  expect_match(
    apa_note(apa_parameters(list(g0, g1)), citations = "keys"),
    "*R*^2^~Tjur~\u00A0=\u00A0Tjur's coefficient of discrimination [@tjurCoefficientsDeterminationLogistic2009]",
    fixed = TRUE
  )
  expect_match(
    apa_note(apa_parameters(list(g0, g1), performance_layout = "columns")),
    "&Delta;*R*^2^~Tjur~\u00A0=\u00A0change in *R*^2^~Tjur~",
    fixed = TRUE
  )
})

test_that("citation keys are found in Pandoc citations but not e-mail addresses", {
  expect_equal(
    apa7:::citation_keys(c(
      "Holm's method [@holmSimpleSequentiallyRejective1979].",
      "As @cheungModelingDependentEffect2014 showed; see [-@a; @b:2020].",
      "Write to someone@example.com."
    )),
    c("holmSimpleSequentiallyRejective1979", "cheungModelingDependentEffect2014", "a", "b:2020")
  )
  expect_equal(apa7:::citation_keys(c(NA, "No citations.")), character(0))
})

test_that("flextables whose notes cite references record the keys", {
  ft <- flextable::flextable(head(cars, 2))
  expect_identical(apa7:::add_note_citations(ft, "No citations."), ft)
  cited <- apa7:::add_note_citations(ft, "Holm's method [@holmSimpleSequentiallyRejective1979].")
  expect_s3_class(cited, "apa7_cited")
  expect_s3_class(cited, "flextable")
  expect_equal(attr(cited, "apa7_citations"), "holmSimpleSequentiallyRejective1979")
  # Not a flextable: unchanged
  expect_identical(apa7:::add_note_citations(head(cars, 2), "[@x]"), head(cars, 2))

  # apa_flextable(note = TRUE) and apa_cor() record the keys of their notes
  withr::local_options(apa7.citations = "keys")
  skip_if_not_installed("correlation")
  tbl <- apa_flextable(apa_cor(correlation::correlation(mtcars[, c("mpg", "wt", "hp")])), note = TRUE)
  expect_equal(attr(tbl, "apa7_citations"), "holmSimpleSequentiallyRejective1979")
  tbl_text <- apa_flextable(apa_cor(mtcars[, c("mpg", "wt")]), note = "Custom note.")
  expect_false(inherits(tbl_text, "apa7_cited"))
  ft_note <- apa_flextable(head(cars, 2), note = "As in [@lakensCalculatingReportingEffect2013].")
  expect_equal(attr(ft_note, "apa7_citations"), "lakensCalculatingReportingEffect2013")
})

test_that("note citations are added to nocite when the table is printed", {
  ft <- apa7:::add_note_citations(
    flextable::flextable(head(cars, 2)),
    "[@holmSimpleSequentiallyRejective1979]"
  )
  # Outside a Pandoc document, the table prints as usual
  local_mocked_bindings(pandoc_to = function(...) NULL, .package = "knitr")
  expect_false(grepl("nocite", paste(knitr::knit_print(ft), collapse = "")))

  local_mocked_bindings(
    pandoc_to = function(...) "html",
    current_input = function(...) "doc.qmd",
    .package = "knitr"
  )
  local_mocked_bindings(document_nocite = function() "@olejnikGeneralizedEtaOmega2003")
  withr::defer(rm("note_citations", envir = apa7:::the))
  out <- paste(knitr::knit_print(ft), collapse = "")
  expect_match(out, "<table", fixed = TRUE)
  expect_match(
    out,
    "---\nnocite: |\n  @olejnikGeneralizedEtaOmega2003\n  @holmSimpleSequentiallyRejective1979\n---",
    fixed = TRUE
  )
  # Each block lists the keys of all tables printed so far in the document
  ft2 <- apa7:::add_note_citations(flextable::flextable(head(cars, 2)), "[@a]")
  out2 <- paste(knitr::knit_print(ft2), collapse = "")
  expect_match(out2, "  @holmSimpleSequentiallyRejective1979, @a\n---", fixed = TRUE)
})

test_that("the articles' copy of apa7.bib matches inst/apa7.bib", {
  # vignettes/articles/apa_more.bib is a copy for renders in which
  # ../../inst/apa7.bib cannot be found. Both files exist only in the source
  # package (not when R CMD check runs the tests on the installed package).
  root <- normalizePath(file.path(testthat::test_path(), "..", ".."), mustWork = FALSE)
  original <- file.path(root, "inst", "apa7.bib")
  copy <- file.path(root, "vignettes", "articles", "apa_more.bib")
  skip_if_not(file.exists(original) && file.exists(copy), "source package files not available")
  read <- function(f) gsub("\r", "", readLines(f, encoding = "UTF-8", warn = FALSE), fixed = TRUE)
  expect_identical(read(copy), read(original))
})

Try the apa7 package in your browser

Any scripts or data that you put into this service are public.

apa7 documentation built on Dec. 1, 2026, 5:06 p.m.