Skip to content

Commit ff4d7c5

Browse files
Robustness: dim() can return NA
1 parent e35122a commit ff4d7c5

File tree

3 files changed

+32
-3
lines changed

3 files changed

+32
-3
lines changed

R/expect-shape.R

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ expect_shape = function(object, ..., length, nrow, ncol, dim) {
3737
act$nrow <- dim_object[1L]
3838

3939
expect(
40-
act$nrow == nrow,
40+
identical(as.integer(act$nrow), as.integer(nrow)),
4141
sprintf("%s has %i rows, not %i.", act$lab, act$nrow, nrow)
4242
)
4343
} else if (!missing(ncol)) {
@@ -49,7 +49,7 @@ expect_shape = function(object, ..., length, nrow, ncol, dim) {
4949
act$ncol <- dim_object[2L]
5050

5151
expect(
52-
act$ncol == ncol,
52+
identical(as.integer(act$ncol), as.integer(ncol)),
5353
sprintf("%s has %i columns, not %i.", act$lab, act$ncol, ncol)
5454
)
5555
} else { # !missing(dim)
@@ -61,7 +61,7 @@ expect_shape = function(object, ..., length, nrow, ncol, dim) {
6161
)
6262

6363
expect(
64-
isTRUE(all(act$dim == dim)),
64+
identical(as.integer(act$dim), as.integer(dim)),
6565
sprintf("%s has shape (%s), not (%s).", act$lab, toString(act$dim), toString(dim))
6666
)
6767
}

tests/testthat/_snaps/expect-shape.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,18 @@
3838

3939
array() has only one dimension.
4040

41+
# NA handling (e.g. dbplyr)
42+
43+
`x` has NA rows, not 10.
44+
45+
---
46+
47+
`x` has 10 columns, not NA.
48+
49+
---
50+
51+
`x` has shape (NA, 10), not (10, NA).
52+
4153
# at least one argument is required
4254

4355
Code

tests/testthat/test-expect-shape.R

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,26 @@ test_that("uses S3 dim method", {
4343
dim.testthat_expect_shape <- function(x) 1:2
4444
x <- integer()
4545
class(x) <- "testthat_expect_shape"
46+
registerS3method("dim", "testthat_expect_shape", dim.testthat_expect_shape)
47+
4648
expect_success(expect_shape(x, dim = 1:2))
4749
})
4850

51+
test_that("NA handling (e.g. dbplyr)", {
52+
dim.testthat_expect_shape_missing <- function(x) c(NA_integer_, 10L)
53+
x <- integer()
54+
class(x) <- "testthat_expect_shape_missing"
55+
registerS3method("dim", "testthat_expect_shape_missing", dim.testthat_expect_shape_missing)
56+
57+
expect_success(expect_shape(x, nrow = NA_integer_))
58+
expect_success(expect_shape(x, ncol = 10L))
59+
expect_success(expect_shape(x, dim = c(NA_integer_, 10L)))
60+
61+
expect_snapshot_failure(expect_shape(x, nrow = 10L))
62+
expect_snapshot_failure(expect_shape(x, ncol = NA_integer_))
63+
expect_snapshot_failure(expect_shape(x, dim = c(10L, NA_integer_)))
64+
})
65+
4966
test_that("uses S4 dim method", {
5067
A <- setClass("ExpectShapeA", slots = c(x = "numeric", y = "numeric"))
5168
setMethod("dim", "ExpectShapeA", function(x) 8:10)

0 commit comments

Comments
 (0)