R devtools test() 错误,但 testThat test_file() 有效



我在正在构建的包中有一个函数,该函数将十六进制代码分配给全局环境以供分析师使用...

optiplum<-function(){
  assign(
    x="optiplum",
    value=rgb(red=129,green=61,blue=114, maxColorValue = 255),
    envir=.GlobalEnv)
  }

我的单元测试代码是:

test_that("optiplum - produces the correct hex code",{
 optiplum()
  expect_true(identical(optiplum,"#813D72"))
})

当我手动运行代码时,没有错误:

> str(optiplum)
 chr "#813D72"
> str("#813D72")
 chr "#813D72"
> identical("#813D72",optiplum)
[1] TRUE
> expect_true(identical(optiplum,"#813D72"))

当我运行test_file()时也不会出错

> test_file("./tests/testthat/test-optiplum.R")
optiplum : .

但是,当我在开发工具工作流中运行测试时:

> test()
Testing optINTERNAL
Loading optINTERNAL
optiplum : 1

1. Failure: optiplum - produces the correct hex code --------------------------------------------------------------------------------------------------------------
identical(optiplum, "#813D72") isn't true

任何人都对为什么会发生这种情况以及我如何解决这种情况有任何想法?

分配给全局环境是禁忌,请参阅 R Inferno 和 test尽可能隔离测试(详见test_that())。 因此,对全球环境的optiplum()分配不会成功,因为测试功能严格禁止这种行为。

@Hadley正确地指出,该函数应该只返回字符串而不是赋值它,特别是因为每次使用它只有两个额外的字符。

所以不是

optiplum<-function(){
  assign(
    x="optiplum",
    value=rgb(red=129,green=61,blue=114, maxColorValue = 255),
    envir=.GlobalEnv)
  }

optiplum <- function() rgb(red=102,green=17,blue=109, maxColorValue = 255)

最新更新