gpt4 book ai didi

unit-testing - 如何 reshape S3 对象以使其具有可比性?

转载 作者:行者123 更新时间:2023-12-04 06:16:12 25 4
gpt4 key购买 nike

我使用 test_that 进行单元测试,我正在尝试比较两个对象。在某些情况下,无论内容如何,​​这两个对象似乎永远不会相同( expect_identical ),但如果它们属于同一类,则可以相等( expect_equal )。我确定这与类的构造方式有关(我正在使用 R.oo)

那么......是否可以 reshape /展平/重组一个对象(可能成为一个列表?)以便提取原始数据,从而使两个对象具有可比性?我意识到这可能是一项不可能完成的任务。我对 R 中的环境知之甚少,无法确定。

编辑
这是一个例子:

library(R.oo)
library(testthat)

setConstructorS3( "MyClass" , function( )
{
extend( Object() , "MyClass" ,
.param1 = rnorm(10)
)
} )

test1 = MyClass()
test2 = MyClass()
expect_identical(test1, test2) # error: Objects equal but not identical
expect_equal( test1, test2) # no error reported

最佳答案

str 进行一些互动探索引导我这样做:

as.list.Object <- function(x, ...) {
vars <- as.list(attr(x, ".env"), all = TRUE)

vars[substr(names(vars), 1, 3) != "..."]
}

all.equal.Object <- function(target, current, ...) {
all.equal(as.list(target), as.list(current), ...)
}

expect_equal(test1, test2)
# Error: test1 not equal to test2
# Component 1: Mean relative difference: 1.056427

关于unit-testing - 如何 reshape S3 对象以使其具有可比性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7209885/

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