Skip to content

Commit

Permalink
Add expect_type
Browse files Browse the repository at this point in the history
Fixes #316.
  • Loading branch information
hadley committed Feb 18, 2016
1 parent 633eb37 commit 3fa7869
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 4 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export(expect_output)
export(expect_silent)
export(expect_that)
export(expect_true)
export(expect_type)
export(expect_warning)
export(expectation)
export(fail)
Expand Down
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# testthat 0.11.0.9000

* `expect_type()` checks the _type_ of the object (#316).

* `not()` has been deprecated.

* `MinimalReporter` correct labels errors with E and failures with F (#311).
Expand Down
20 changes: 18 additions & 2 deletions R/expectations.r
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
#' Expectation: does the object inherit from a class?
#' Expectation: does the object inherit from a S3 or S4 class, or a base type?
#'
#' Tests whether or not an object inherits from any of a list of classes.
#' Tests whether or not an object inherits from any of a list of classes, or
#' is an instance of a base type.
#'
#' @inheritParams expect_that
#' @param class character vector of class names
#' @param type String giving base type (as returned by \code{\link{typeof}}).
#' @seealso \code{\link{inherits}}
#' @family expectations
#' @export
Expand Down Expand Up @@ -36,6 +38,20 @@ is_a <- function(class) {
}
}

#' @export
#' @rdname expect_is
expect_type <- function(expr, type) {
stopifnot(is.character(type), length(type) == 1)

label <- find_expr("expr")
actual_type <- typeof(expr)

expect(
identical(type, actual_type),
paste0("`", label, "` is type `", actual_type, "` not `", type, "`")
)
}

#' Expectation: is the object true/false?
#'
#' These are fall-back expectations that you can use when none of the other
Expand Down
10 changes: 8 additions & 2 deletions man/expect_is.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions tests/testthat/test-expectations.r
Original file line number Diff line number Diff line change
Expand Up @@ -146,3 +146,8 @@ test_that("expected_named optionally ignores case", {
test_that("expected_named optionally ignores order", {
expect_named(c(a = 1, b = 2), c("b", "a"), ignore.order = TRUE)
})


test_that("expect_type checks typeof", {
expect_type(factor("a"), "integer")
})

0 comments on commit 3fa7869

Please sign in to comment.