str("#813D72") ch-6ren">
gpt4 book ai didi

r devtools test() 错误但测试 test_file() 有效

转载 作者:行者123 更新时间:2023-12-01 05:14:49 25 4
gpt4 key购买 nike

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

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 : .

但是,当我将测试作为 devtools 工作流程的一部分运行时:
> test()
Testing optINTERNAL
Loading optINTERNAL
optiplum : 1


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

任何人都知道为什么会发生这种情况以及我如何解决这种情况?

最佳答案

分配给全局环境是一个禁忌,见 R Inferno和 testthat 尽可能隔离测试(请参阅 test_that() 详细信息)。因此,optiplum()分配给全局环境不会成功,因为 testthat 函数严格禁止这种行为。

@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)

关于r devtools test() 错误但测试 test_file() 有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21674798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com