Home > Enterprise >  expect_equal fails due to different keys in data.table
expect_equal fails due to different keys in data.table

Time:05-31

I have written a very simple unit test, but it keeps failing due to a different key in data.table:

out is the actual outcome of my function and expectedOut is something that I have defined:

  extectedOut <- data.table(
    ID = c("ID-1", "ID-2"), 
    Name = c("product-1", "product-2"), 
    type = c("N-1", "N-2")
  )

I have run the unit test using test_that and it fails with the error message:

Datasets has different keys. 'target': ID. 'current' has no key.

they look the same, but looking at the structure one indeed has a key.

> str(out)
Classes ‘data.table’ and 'data.frame':  2 obs. of  3 variables:
 $ ID: chr  "ID-1" "ID-2"
 $ Name: chr  "name-1" "name-2"
 $ type    : chr  "N-1" "N-2"
 - attr(*, "sorted")= chr "ID"
 - attr(*, ".internal.selfref")=<externalptr> 
> str(extectedOut)
Classes ‘data.table’ and 'data.frame':  2 obs. of  3 variables:
 $ ID: chr  "ID-1" "ID-2"
 $ Name: chr  "product-1" "product-2"
 $ type    : chr  "N-1" "N-2"
 - attr(*, ".internal.selfref")=<externalptr> 

How can I avoid this error from happening?

CodePudding user response:

An option is to set the keys of the dataset to NULL before applying the expect_equal

library(data.table)
setkey(out, NULL)

expect_equal is based on all.equal, so we may also use check.attributes as FALSE

> out <- copy(extectedOut)
>setkey(out, "ID")

> expect_equal(extectedOut, out)
Error: `extectedOut` not equal to `out`.
Datasets have different keys. 'target': has no key. 'current': [ID].
> expect_equal(extectedOut, out, check.attributes = FALSE)

CodePudding user response:

You could use expect_equivalent:

library(data.table)
Out <- data.table(
  ID = c("ID-1", "ID-2"), 
  Name = c("product-1", "product-2"), 
  type = c("N-1", "N-2")
)
expectedOut <- data.table(
  ID = c("ID-1", "ID-2"), 
  Name = c("product-1", "product-2"), 
  type = c("N-1", "N-2")
)

setkey(Out,ID)

testthat::expect_equivalent(Out,expectedOut)

testthat::expect_equal(Out,expectedOut)
#> Error: `expectedOut` not equal to `Out`.
#> Datasets has different keys. 'target': ID. 'current' has no key.
  • Related