Debian Codegraph @

tests/testthat/test-defer.R

raw
1
2 test_that("defer evaluates in appropriate environment", {
3
4 foo <- function() {
5 writeLines("+ foo")
6 defer(writeLines("> foo"), environment())
7 defer(writeLines("> foo.parent"), parent.frame(1))
8 defer(writeLines("> foo.parent.parent"), parent.frame(2))
9 writeLines("- foo")
10 }
11
12 bar <- function() {
13 writeLines("+ bar")
14 foo()
15 writeLines("- bar")
16 }
17
18 baz <- function() {
19 writeLines("+ baz")
20 bar()
21 writeLines("- baz")
22 }
23
24 output <- capture.output(baz())
25 expected <- c(
26 "+ baz",
27 "+ bar",
28 "+ foo",
29 "- foo",
30 "> foo",
31 "- bar",
32 "> foo.parent",
33 "- baz",
34 "> foo.parent.parent"
35 )
36
37 expect_identical(output, expected)
38
39 })
40
41 test_that("defer runs handles in LIFO order", {
42 x <- double()
43 local({
44 defer(x <<- c(x, 1))
45 defer(x <<- c(x, 2))
46 defer(x <<- c(x, 3))
47 })
48
49 expect_equal(x, c(3, 2, 1))
50 })
51
52 test_that("defer captures arguments properly", {
53
54 foo <- function(x) {
55 defer(writeLines(x), scope = parent.frame())
56 }
57
58 bar <- function(y) {
59 writeLines("+ bar")
60 foo(y)
61 writeLines("- bar")
62 }
63
64 output <- capture.output(bar("> foo"))
65 expected <- c("+ bar", "- bar", "> foo")
66 expect_identical(output, expected)
67
68 })
69
70 test_that("defer works with arbitrary expressions", {
71
72 foo <- function(x) {
73 defer({
74 x + 1
75 writeLines("> foo")
76 }, scope = parent.frame())
77 }
78
79 bar <- function() {
80 writeLines("+ bar")
81 foo(1)
82 writeLines("- bar")
83 }
84
85 output <- capture.output(bar())
86 expected <- c("+ bar", "- bar", "> foo")
87 expect_identical(output, expected)
88
89 })
90
91
92 test_that("renv_defer_execute can run handlers earlier", {
93 x <- 1
94 defer(rm(list = "x"))
95 expect_true(exists("x", inherits = FALSE))
96 renv_defer_execute(environment())
97 expect_false(exists("x", inherits = FALSE))
98 })
99
100 test_that("renv_scope_options inside catch does not leak", {
101
102 wrapper <- function() {
103 renv_scope_options(renv.test.option = "original")
104 catch({
105 renv_scope_options(renv.test.option = "modified")
106 expect_equal(getOption("renv.test.option"), "modified")
107 })
108 getOption("renv.test.option")
109 }
110
111 expect_equal(wrapper(), "original")
112
113 })
114
115 test_that("assignments inside catch are visible to the caller", {
116
117 wrapper <- function() {
118 x <- 1
119 catch({ x <- 42 })
120 x
121 }
122
123 expect_equal(wrapper(), 42)
124
125 })
126
127 test_that("nested catch scopes correctly", {
128
129 wrapper <- function() {
130 renv_scope_options(renv.test.option = "outer")
131 catch({
132 renv_scope_options(renv.test.option = "middle")
133 catch({
134 renv_scope_options(renv.test.option = "inner")
135 expect_equal(getOption("renv.test.option"), "inner")
136 })
137 expect_equal(getOption("renv.test.option"), "middle")
138 })
139 getOption("renv.test.option")
140 }
141
142 expect_equal(wrapper(), "outer")
143
144 })