Debian Codegraph @

tests/test-cran/test-session.R

raw
1 library(testit)
2
3 assert('do_once() executes the task exactly once', {
4 opt = 'xfun.test.do_once.exec'
5 options(setNames(list(NULL), opt)) # ensure clean state
6 # use an env to share a counter with the nested expression
7 e = new.env(parent = emptyenv()); e$count = 0L
8 suppressMessages(do_once({ e$count = e$count + 1L }, opt))
9 (e$count %==% 1L)
10 # second call is skipped
11 suppressMessages(do_once({ e$count = e$count + 1L }, opt))
12 (e$count %==% 1L)
13 options(setNames(list(NULL), opt))
14 })
15
16 assert('do_once() returns the task value invisibly', {
17 opt = 'xfun.test.do_once.ret'
18 options(setNames(list(NULL), opt))
19 val = suppressMessages(do_once({
20 v = 42L; v
21 }, opt))
22 (val %==% 42L)
23 options(setNames(list(NULL), opt))
24 })
25
26 assert('do_once() emits a hint message and sets option to FALSE', {
27 opt = 'xfun.test.do_once.hint'
28 options(setNames(list(NULL), opt))
29 msgs = character()
30 withCallingHandlers(
31 do_once(invisible(NULL), opt),
32 message = function(m) {
33 msgs <<- c(msgs, conditionMessage(m))
34 invokeRestart('muffleMessage')
35 }
36 )
37 # the hint message should mention the option name
38 (any(grepl(opt, msgs, fixed = TRUE)))
39 # option is now FALSE so subsequent calls are no-ops
40 (identical(getOption(opt), FALSE))
41 options(setNames(list(NULL), opt))
42 })
43
44 assert('do_once() is a no-op when option is already FALSE', {
45 opt = 'xfun.test.do_once.noop'
46 options(setNames(list(FALSE), opt))
47 e = new.env(parent = emptyenv()); e$count = 0L
48 res = do_once({ e$count = e$count + 1L; 99L }, opt)
49 (e$count %==% 0L)
50 (is.null(res))
51 options(setNames(list(NULL), opt))
52 })
53
54 assert('do_once() with hint = "" emits no extra message', {
55 opt = 'xfun.test.do_once.nohint'
56 options(setNames(list(NULL), opt))
57 msgs = character()
58 withCallingHandlers(
59 do_once(invisible(NULL), opt, hint = ''),
60 message = function(m) {
61 msgs <<- c(msgs, conditionMessage(m))
62 invokeRestart('muffleMessage')
63 }
64 )
65 (length(msgs) %==% 0L)
66 options(setNames(list(NULL), opt))
67 })
68