Skip to content

Commit cdb15a2

Browse files
refactor for clarity, add tests
1 parent e89fff9 commit cdb15a2

File tree

2 files changed

+22
-23
lines changed

2 files changed

+22
-23
lines changed

R/expect-length.R

Lines changed: 17 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -62,50 +62,44 @@ expect_shape = function(object, shape, nrow, ncol) {
6262
}
6363

6464
act <- quasi_label(enquo(object), arg = "object")
65-
# testing dim
65+
6666
if (missing(nrow) && missing(ncol)) {
67+
# testing dim
68+
if (missing(shape)) {
69+
stop("`shape` must be provided if `nrow` and `ncol` are not")
70+
}
6771
act$shape <- dim_object
6872

6973
expect(
7074
isTRUE(all.equal(act$shape, shape)),
7175
sprintf("%s has shape (%s), not (%s).", act$lab, toString(act$shape), toString(shape))
7276
)
73-
74-
return(act$val)
75-
}
76-
77-
# testing only ncol
78-
if (missing(nrow)) {
77+
} else if (missing(nrow) && !missing(ncol)) {
78+
# testing only ncol
7979
act$ncol <- dim_object[2L]
8080

8181
expect(
8282
act$ncol == ncol,
8383
sprintf("%s has %i columns, not %i.", act$lab, act$ncol, ncol)
8484
)
85-
86-
return(act$val)
87-
}
88-
89-
# testing only nrow
90-
if (missing(ncol)) {
85+
} else if (!missing(nrow) && missing(ncol)) {
86+
# testing only nrow
9187
act$nrow <- dim_object[1L]
9288

9389
expect(
9490
act$nrow == nrow,
9591
sprintf("%s has %i rows, not %i.", act$lab, act$nrow, nrow)
9692
)
93+
} else {
94+
# testing both nrow & ncol (useful, e.g., for testing dim(.)[1:2] for arrays
95+
act$nrow <- dim_object[1L]
96+
act$ncol <- dim_object[2L]
9797

98-
return(act$val)
98+
expect(
99+
act$nrow == nrow && act$ncol == ncol,
100+
sprintf("%s has %i rows and %i columns, not %i rows and %i columns", act$lab, act$nrow, act$ncol, nrow, ncol)
101+
)
99102
}
100103

101-
# testing both nrow & ncol (useful, e.g., for testing dim(.)[1:2] for arrays
102-
act$nrow <- dim_object[1L]
103-
act$ncol <- dim_object[2L]
104-
105-
expect(
106-
act$nrow == nrow && act$ncol == ncol,
107-
sprintf("%s has %i rows and %i columns, not %i rows and %i columns", act$lab, act$nrow, act$ncol, nrow, ncol)
108-
)
109-
110104
return(act$val)
111105
}

tests/testthat/test-expect-shape.R

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,8 @@ test_that("returns input", {
4444
out <- expect_shape(x, 2)
4545
expect_identical(out, x)
4646
})
47+
48+
test_that("at least one argument is required", {
49+
expect_error(expect_shape(1:10), "`shape` must be provided for one-dimensional inputs", fixed = TRUE)
50+
expect_error(expect_shape(cbind(1:2)), "`shape` must be provided if `nrow` and `ncol` are not")
51+
})

0 commit comments

Comments
 (0)