【问题标题】:How do I resolve "cannot add bindings to a locked environment" when working with setRefClass in R在 R 中使用 setRefClass 时如何解决“无法将绑定添加到锁定的环境”
【发布时间】:2021-12-29 20:18:41
【问题描述】:

我在 R 中有一个函数如下

DrawDistroGenerationClass <- function(in_hourStr, in_data){
  
  me <- methods::setRefClass(
    ## Define the environment where this list is defined so
    ## that I can refer to it later.
    "Draw",
    fields = list(hourStr = "character",
                  data = "numeric"),
    
    methods = list(
      getModel = function(){
        return("Draw Distro")
    },
      getName = function(){
        return(hourStr)
    },
      #' 
      #' @param strName the data to be drawn from
      #' @return the new hours value
      generateHoursFromStorage = function(strName){
  

        indSelect <- stats::runif(1, min = 1, max = length(data))
          
        componentLife <- data[indSelect]
        
        return(componentLife)
    }
    )
  )
  ## Set the name for the class
  newMe <- me$new(hourStr = in_hourStr, data = in_data)
  return(newMe)
}

测试看起来像......

test_that("test Time2Repair-DrawDistroHoursGenerationClass", {
  
  distroHoursGenerationClass <- DrawDistroHoursGenerationClass("test", c(0.0, 1.0, 2.0, 3.0))
  
  
  testthat::expect_equal(distroHoursGenerationClass$getModel(), "Draw Distro")
  
  testthat::expect_equal(distroHoursGenerationClass$getName(), "test")
  
  testthat::expect_true(is.numeric(distroHoursGenerationClass$generateHoursFromStorage("test")))
  
}
)

目的是我可以使用标签和一组值调用函数 DrawDistroGenerationClass,并生成一个函数,该函数将在调用时从该集合中随机抽取。

该功能有效,但在我的 R 项目中,我对此功能有一个单元测试(testthat),当我运行 R cmd 时,我得到:

  1. -methods::setRefClass(...)
  2. -methods::setClass(...)
  3. -methods::assignClassDef(Class, classDef, where)
  4. -base::assign(mname, def, where)

assign(mname, def, where) 中的错误:无法将绑定添加到锁定的环境”。

我不知道为什么会出现这个问题/

我宁愿不让我的输入变量全局化(因为它们可能与其他类冲突),我在这里使用 setRefClass 方法,因此我可以制作这个函数的许多独立版本。

【问题讨论】:

  • 在您分享重现错误的测试代码之前,我们无法开始诊断错误。
  • RPost 已更新测试。单独运行测试通过,但是当使用 R cmd check 运行测试时(在项目中)它失败并报告错误。

标签: r unit-testing oop


【解决方案1】:

锁定的环境通常归结为以下两种情况之一。

  1. 最终试图抓住他们所描述的东西的坏 cmet。

  2. 错误的包加载。当包以正常方式而不是通过 devtools 加载时,它们会被锁定,因此 R 无法修改它们。

看起来你可能有一些不好的 cmets。但您也可能在此代码之外的其他地方重复调用包。

【讨论】:

  • 我已经删除了 cmets 并重新运行测试,但错误保持不变。不过,我不确定我是否理解您的 #2 评论。
猜你喜欢
  • 2019-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-11
  • 2022-06-12
  • 2010-10-12
  • 2020-02-03
  • 1970-01-01
相关资源
最近更新 更多