Debian Codegraph @

tests/testit/test-cache.R

raw
1 library(testit)
2
3 dep_list$restore()
4 knit_code$restore()
5
6
7 assert('find_symbols() identifies all symbols', {
8 (find_symbols('x = x + 1; rnorm(1, std = z)') %==% c('x', 'rnorm', 'z'))
9 })
10
11 knit_lazy = function(lazy = TRUE) {
12 in_dir(tempdir(), {
13 txt = c(sprintf('```{r test, cache=TRUE, cache.lazy=%s}', lazy),
14 'x1 = Sys.time()', '```')
15 knit(text = txt, quiet = TRUE)
16 x2 = x1
17 Sys.sleep(0.1)
18 knit(text = txt, quiet = TRUE)
19 x1 == x2 # x1 should not be updated
20 })
21 }
22 assert('cache.lazy = TRUE/FALSE works', {
23 (knit_lazy(TRUE))
24 (knit_lazy(FALSE))
25 })
26
27 knit_code$set(a = 1, b = 2, c = 3)
28 assert('dep_prev() sets dependencies on previous chunks', {
29 # dependency is empty now
30 (dep_list$get() %==% list())
31 # b/c depend on a, c depends on b
32 dep_prev()
33 (dep_list$get() %==% list(a = c('b', 'c'), b = 'c'))
34 })
35 dep_list$restore()
36 knit_code$restore()
37
38 assert('dep_auto() solves dependencies', {
39 # dependency is empty now
40 (dep_list$get() %==% list())
41
42 # base rmd text
43 rmd0 = c(
44 '```{r, autodep=TRUE, cache=TRUE}',
45 'x = %s',
46 '```',
47 '```{r, autodep=TRUE, cache=TRUE}',
48 'print(x)',
49 '```'
50 )
51
52 td = tempfile()
53 dir.create(td, showWarnings = FALSE, recursive = TRUE)
54
55 rmd1 = sprintf(rmd0, 'runif(1)')
56 rmd2 = sprintf(rmd0, '"a"')
57
58 # without child document
59 in_dir(td, {
60 # with cache, the result should reproduce
61 knit1 = knit(text = rmd1, quiet = TRUE)
62 (knit(text = rmd1, quiet = TRUE) %==% knit1)
63
64 # on updating `x`, the printed result should change
65 knit2 = knit(text = rmd2, quiet = TRUE)
66 print2 = gsub('\n.*', '', gsub('.*\n##', '##', knit2))
67 (print2 %==% '## [1] "a"')
68 })
69 })
70 dep_list$restore()
71 knit_code$restore()
72
73 assert('dep_auto() solves dependencies of child documents', {
74 # dependency is empty now
75 (dep_list$get() %==% list())
76
77 # base rmd text
78 rmd0 = c(
79 '```{r, autodep=TRUE, cache=TRUE}',
80 'x = %s',
81 '```',
82 '```{r, autodep=TRUE, cache=TRUE}',
83 'print(x)',
84 '```'
85 )
86 rmd1 = sprintf(rmd0, 'runif(1)')
87 rmd2 = sprintf(rmd0, '"a"')
88
89 td = tempfile()
90 dir.create(td, showWarnings = FALSE, recursive = TRUE)
91
92 # with child document
93 parent = c(
94 '```{r, child="child.Rmd"}',
95 '```'
96 )
97 in_dir(td, {
98 # with cache, the result should reproduce
99 writeLines(rmd1, 'child.Rmd')
100 knit1 = knit(text = parent, quiet = TRUE)
101 (knit(text = parent, quiet = TRUE) %==% knit1)
102
103 # on updating `x`, the printed result should change
104 writeLines(rmd2, 'child.Rmd')
105 knit2 = knit(text = parent, quiet = TRUE)
106 print2 = gsub('\n.*', '', gsub('.*\n##', '##', knit2))
107 (print2 %==% '## [1] "a"')
108 })
109 })
110 dep_list$restore()
111 knit_code$restore()