object no found error in testthat tests

情到浓时终转凉″ 提交于 2019-12-20 06:00:29

问题


Here is the code:

setGeneric("ifLet",
        function(sym, x, body1, body2, ...) {
            standardGeneric("ifLet")
        })

#' @name ifLet
#' @export 
setMethod("ifLet",
        signature(sym = "name", x = "ANY", body1 = "ANY", body2 = "ANY"),
        function(sym, x, body1, body2 = {}) {
            e = new.env()
            sym_str = deparse(substitute(sym))
            ifLet(sym_str, x, body1, body2)
        })

#' @rdname ifLet
#' @export 
setMethod("ifLet",
        signature(sym = "character", x = "ANY", body1 = "ANY", body2 = "ANY"),
        function(sym, x, body1, body2 = {}) {
            stopifnot(length(sym) == 1)
            e = new.env()
            e[[sym]] = x
            if(e[[sym]]) {
                eval(substitute(body1), e)
            } else {
                eval(substitute(body2), e)
            }
        })

# test
ifLet("myvar", 3 > 2, {
            as.integer(myvar) * 3
        }, {
            as.integer(myvar) + 1
        }) == 3

The test passes in a reple but fails in a testthat context, why?

Here is the error msg:

1. Error: ifLet ----------------------------------------------------------------
object 'myvar' not found
1: withCallingHandlers(eval(code, new_test_environment), error = capture_calls)
2: eval(code, new_test_environment)
3: eval(expr, envir, enclos)
4: ifLet("myvar", 3 > 2, {
   as.integer(myvar) * 3
   }, {
   as.integer(myvar) + 1
   }) at test.bedinfo.R:60
5: ifLet("myvar", 3 > 2, {
   as.integer(myvar) * 3
   }, {
   as.integer(myvar) + 1
   }) at /Users/kaiyin/EclipseWorkspace/CollapsABEL/R/0_ifLen.R:58
6: .local(sym, x, body1, body2, ...)
7: eval(substitute(body1), e) at /Users/kaiyin/EclipseWorkspace/CollapsABEL/R/0_ifLen.R:80
8: eval(expr, envir, enclos)
9: .handleSimpleError(function (e) 
   {
   e$calls <- head(sys.calls()[-seq_len(frame + 7)], -2)
   signalCondition(e)
   }, "object 'myvar' not found", quote(eval(expr, envir, enclos))) at test.bedinfo.R:61

来源:https://stackoverflow.com/questions/30563122/object-no-found-error-in-testthat-tests

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!