Debian Codegraph @

tests/test-ci/test-cache.R

raw
1 library(testit)
2
3 assert('find_globals() identifies global variables', {
4 env = list2env(
5 list(qwer = 1, g = 2, y = 3, d = 4, z = 5), parent = emptyenv()
6 )
7 # nothing from outside environment
8 (find_globals('x=1', env) %==% character(0))
9 # qwer must be created outside somewhere
10 (find_globals('a=1; b=a; d=qwer', env) %==% 'qwer')
11 (find_globals('a=function(){f=2;g}', env) %==% 'g')
12 # y was assigned locally in z, but there is another y outside from nowhere
13 (find_globals('z=function(){y=1};y', env) %==% 'y')
14 # more complicated cases: operators, subscripts, ...
15 (find_globals(c('a=1%*%1%o%2 %in% d', 'b=d%%10+3%/%2-z[1:3]'), env) %==% c('d', 'z'))
16 })
17
18 assert('global_vars() returns values of global variables in code', {
19 e = new.env(parent = emptyenv())
20 e$x = 42
21 res = global_vars('y = x + 1', e)
22 (is.list(res))
23 ('x' %in% names(res))
24 (res$x %==% 42)
25 })
26
27 assert('md5_obj() computes md5 hash for a character vector or object', {
28 h1 = md5_obj(c('a', 'b'))
29 h2 = md5_obj(c('a', 'b'))
30 h3 = md5_obj(c('a', 'c'))
31 (h1 %==% h2)
32 (h1 != h3)
33 (nchar(h1) %==% 32L)
34 })
35
36 assert('clean_cache() removes old cache files with same base name', {
37 d = tempfile()
38 dir.create(d)
39 base = 'mycode'
40 ext = 'rds'
41 old_hash = paste(rep('a', 32), collapse = '')
42 new_hash = paste(rep('b', 32), collapse = '')
43 old_file = file.path(d, sprintf('%s_%s.%s', base, old_hash, ext))
44 new_file = file.path(d, sprintf('%s_%s.%s', base, new_hash, ext))
45 writeLines('old', old_file)
46 clean_cache(new_file, ext) # should remove old_file
47 (!file.exists(old_file))
48 unlink(d, recursive = TRUE)
49 })
50
51 assert('cache_rds() caches an expression to disk', {
52 d = tempfile()
53 dir.create(d)
54 f = 'mycode.rds'
55 # first call evaluates and caches
56 r1 = cache_rds(1 + 1, file = f, dir = paste0(d, '/'))
57 (r1 %==% 2)
58 # second call loads from cache
59 r2 = cache_rds(1 + 1, file = f, dir = paste0(d, '/'))
60 (r2 %==% 2)
61 # rerun = TRUE forces re-evaluation
62 r3 = cache_rds(1 + 1, file = f, dir = paste0(d, '/'), rerun = TRUE)
63 (r3 %==% 2)
64 unlink(d, recursive = TRUE)
65 })