r devtools test()错误,但测试了test_file()是否有效 [英] r devtools test() errors but testthat test_file() works
问题描述
我正在构建的程序包中有一个函数,该函数将十六进制代码分配给全局环境以供分析人员使用...
I have a function in a package I'm building that assigns a hex-code to the global environment for use by analysts...
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"))
})
当我手动运行代码时,没有错误:
When I run the code manually, there isn't an error:
> str(optiplum)
chr "#813D72"
> str("#813D72")
chr "#813D72"
> identical("#813D72",optiplum)
[1] TRUE
> expect_true(identical(optiplum,"#813D72"))
当我运行一个test_file()时也没有错误
When I run a test_file() is also does not error
> test_file("./tests/testthat/test-optiplum.R")
optiplum : .
但是,当我将测试作为我的devtools工作流程的一部分运行时:
However, when I run the test as part of my devtools workflow:
> test()
Testing optINTERNAL
Loading optINTERNAL
optiplum : 1
1. Failure: optiplum - produces the correct hex code --------------------------------------------------------------------------------------------------------------
identical(optiplum, "#813D72") isn't true
任何人都知道为什么会发生这种情况以及如何解决这种情况?
Anyone have any ideas on why this might be occurring and how I can resolve the situation?
推荐答案
Assignment to the global environment is a no-no, see R Inferno and testthat isolates tests as much as possible (see test_that()
details). As a consequence, the optiplum()
assignment to the global environment would not succeed because the testthat function strictly prohibits such behaviour.
@Hadley正确地指出,该函数应仅返回字符串而不是对其进行赋值,特别是因为每次使用时它仅是两个额外的字符.
@Hadley rightly points out that the function should just return the string instead of assigning it, particularly since it is just two extra characters for each use.
不是
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()是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!