Debian Codegraph @

tests/testthat/test-gc.r

raw symbols SCIP
1 test_that("unreferenced observers are garbage collected", {
2 vals_removed <- FALSE
3 obs_removed <- FALSE
4 vals <- reactiveValues(A=1)
5 obs <- observe({ vals$A })
6
7 # These are called when the objects are garbage-collected
8 reg.finalizer(.subset2(vals,'impl'), function(e) vals_removed <<- TRUE)
9 reg.finalizer(obs, function(e) obs_removed <<- TRUE)
10
11 flushReact()
12
13 # Removing this reference to obs doesn't delete it because vals still has a
14 # reference to it
15 rm(obs)
16 invisible(gc())
17 expect_equal(c(vals_removed, obs_removed), c(FALSE, FALSE))
18
19 # Updating vals$A and flushing won't make obs go away because it creates a new
20 # context, and vals$A's context tracks obs's context as a dependent
21 vals$A <- 2
22 flushReact()
23 invisible(gc())
24 expect_equal(c(vals_removed, obs_removed), c(FALSE, FALSE))
25
26 # Removing vals will result in vals and obs being garbage collected since
27 # there are no other references to them
28 rm(vals)
29 invisible(gc())
30 expect_equal(c(vals_removed, obs_removed), c(TRUE, TRUE))
31 })
32
33
34 test_that("suspended observers are garbage collected", {
35 vals_removed <- FALSE
36 obs_removed <- FALSE
37 vals <- reactiveValues(A=1)
38 obs <- observe({ vals$A })
39
40 # These are called when the objects are garbage-collected
41 reg.finalizer(.subset2(vals,'impl'), function(e) vals_removed <<- TRUE)
42 reg.finalizer(obs, function(e) obs_removed <<- TRUE)
43
44 flushReact()
45
46 vals$A <- 2
47 flushReact()
48 invisible(gc())
49
50 # Simply suspending and removing our reference to obs doesn't result in GC,
51 # because vals's context still has a reference to obs's context, as a dependent
52 obs$suspend()
53 rm(obs)
54 invisible(gc())
55 expect_equal(c(vals_removed, obs_removed), c(FALSE, FALSE))
56
57 # Next time we update vals$A and flush, there's no more reference to obs
58 vals$A <- 3
59 flushReact()
60 invisible(gc())
61 expect_equal(c(vals_removed, obs_removed), c(FALSE, TRUE))
62
63 # Deleting vals should work immediately now
64 rm(vals)
65 invisible(gc()) # Removes vals object
66 expect_equal(c(vals_removed, obs_removed), c(TRUE, TRUE))
67 })