r-style: testthat box prologue, imports-omitted note, box::reload, Rmd-setup policy

This commit is contained in:
Łukasz Boryń 2026-06-08 22:05:34 +02:00
parent fe050e9092
commit 399790b43b
5 changed files with 105 additions and 0 deletions

View File

@ -65,6 +65,57 @@ Keep `box::export()` deliberately small — see
[../tdd-bdd/deep-modules-r.md](../tdd-bdd/deep-modules-r.md). Every name [../tdd-bdd/deep-modules-r.md](../tdd-bdd/deep-modules-r.md). Every name
you export is a contract you owe future callers and tests. you export is a contract you owe future callers and tests.
## `.Rmd` setup chunks — no exception
The rule is the same for `.Rmd` setup chunks as for `.R` files: **no
`library()`, no `source()`**. Migrated bookdown chapters open with a
single `box::use(...)` block and call `knitr::opts_chunk$set(...)` with
explicit `::` namespacing — never `library(knitr)`.
```r
# Rmd/indication/<chapter>.Rmd — migrated style
box::use(targets[tar_read])
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
```
**The one documented exception** is a *legacy-script bridge*: when a
chapter must `sys.source()` an older script that resolves bare names
(e.g. `data.table`, `dplyr`) at top level. The shim must (a) carry a
comment explaining *why* it isn't using `box::use`, and (b) be tracked
as a migration target — not a precedent. Example from the repo:
```r
# Legacy script shim: source `legacy_analysis.R` into a private env
# (parent = globalenv) so its many intermediate bindings do NOT leak
# into sibling chapters. ...
library(data.table); library(dplyr); library(tibble); library(stringr); library(magrittr)
box::use(R/base/utility_fn[get_ensembl_link])
hom_env <- new.env(parent = globalenv())
sys.source("R/indication/legacy_script.R", envir = hom_env)
```
Two infrastructure pieces support this policy:
- `R/base/render_book.R` sets `options(box.path = project_root)` so
`box::use(R/...)` resolves regardless of bookdown's working directory.
- The same file anchors the knit env to `globalenv()` so legacy bare-name
lookups still work *without* breaking `box::use` bindings.
## Reloading modules — `box::reload()`
`box::use` caches modules across the R session. When you've edited a
module and want the change to take effect in the same session — testing
in the REPL, iterating in a `diagnose` loop, re-rendering a chapter —
call:
```r
box::reload(R/indication/client) # drops the cache; next box::use re-evaluates
```
Use this in `feedback-loops-r.md` loops where determinism matters more
than speed. See
[`../diagnose/feedback-loops-r.md`](../diagnose/feedback-loops-r.md#make-the-loop-deterministic).
## Anti-patterns ## Anti-patterns
### `library()` at the top of a file — BAD ### `library()` at the top of a file — BAD

View File

@ -3,6 +3,10 @@
Follows the [Tidyverse style guide](https://style.tidyverse.org/) where it Follows the [Tidyverse style guide](https://style.tidyverse.org/) where it
matches the project's idiom. Four substitutions matter most. matches the project's idiom. Four substitutions matter most.
> Snippets below show only the function bodies; the `box::use(...)`
> prologue is omitted for clarity. Real files start with one — see
> [box.md](box.md).
## <a id="for-loops"></a>1. `for` loops → `purrr` mapping ## <a id="for-loops"></a>1. `for` loops → `purrr` mapping
### Bad — real example, list-column flattening ### Bad — real example, list-column flattening

View File

@ -2,6 +2,10 @@
Three rules. Apply them before writing the test, not after. Three rules. Apply them before writing the test, not after.
> Snippets below show only the function bodies; the `box::use(...)`
> prologue is omitted for clarity. Real files start with one — see
> [`../r-style/box.md`](../r-style/box.md).
## 1. Dependency injection — pass clients, don't construct them ## 1. Dependency injection — pass clients, don't construct them
Functions that build their own dependencies are hard to test because the Functions that build their own dependencies are hard to test because the

View File

@ -2,6 +2,10 @@
**Mock at system boundaries. Never mock your own code.** **Mock at system boundaries. Never mock your own code.**
> Snippets below show only the function bodies; the `box::use(...)`
> prologue is omitted for clarity. Real files start with one — see
> [`../r-style/box.md`](../r-style/box.md).
## Boundaries you may mock ## Boundaries you may mock
- HTTP / REST APIs — `httptest2`, `webmockr`, or `httr2::with_mocked_responses()`. - HTTP / REST APIs — `httptest2`, `webmockr`, or `httr2::with_mocked_responses()`.

View File

@ -7,6 +7,48 @@ core tdd-bdd loop in an R repo.
--- ---
## Test-file prologue (`box::use` for testthat)
Every test file under `tests/testthat/**/test_*.R` opens with the same
three blocks:
```r
# R
project_root <- normalizePath(file.path(
testthat::test_path(), "..", "..", ".."
))
options(box.path = project_root)
box::use(
testthat[
describe, it,
expect_true, expect_false, expect_equal, expect_error,
expect_type, expect_identical, expect_null, expect_silent
]
)
box::use(
R/indication/get_modb_bulk_config[get_dataset_config],
R/indication/query_modb[get_modb_client]
)
```
Why each block:
- **`testthat::test_path()` walk-up + `options(box.path = ...)`** anchors
`box::use(R/...)` resolution to the repo root regardless of where
`testthat::test_dir()` set the working directory.
- **`box::use(testthat[...])`** — bare-name imports of every `describe`,
`it`, and `expect_*` the file calls. No `library(testthat)`.
- **Separate `box::use(R/.../module[...])` block** for the system under
test, alphabetised, named imports only.
Snippets below show only the `describe(...) { it(...) ... }` body — the
prologue is implied. When writing a new test file, copy this prologue
verbatim.
---
## Characteristics — what makes a test good or bad ## Characteristics — what makes a test good or bad
Use this rubric before writing any `it(...)` block. The paired examples Use this rubric before writing any `it(...)` block. The paired examples