Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

inheritance-expectations

Does code return an object inheriting from the expected base type, S3 class, or S4 class?


Description

See https://adv-r.hadley.nz/oo.html for an overview of R's OO systems, and the vocabulary used here.

  • expect_type(x, type) checks that typeof(x) is type.

  • expect_s3_class(x, class) checks that x is an S3 object that inherits() from class

  • expect_s3_class(x, NA) checks that x isn't an S3 object.

  • expect_s4_class(x, class) checks that x is an S4 object that is() class.

  • expect_s4_class(x, NA) checks that x isn't an S4 object.

See expect_vector() for testing properties of objects created by vctrs.

Usage

expect_type(object, type)

expect_s3_class(object, class, exact = FALSE)

expect_s4_class(object, class)

Arguments

object

Object to test.

Supports limited unquoting to make it easier to generate readable failures within a function or for loop. See quasi_label for more details.

type

String giving base type (as returned by typeof()).

class

Either a character vector of class names, or for expect_s3_class() and expect_s4_class(), an NA to assert that object isn't an S3 or S4 object.

exact

If FALSE, the default, checks that object inherits from class. If TRUE, checks that object has a class that's identical to class.

See Also

Examples

x <- data.frame(x = 1:10, y = "x", stringsAsFactors = TRUE)
# A data frame is an S3 object with class data.frame
expect_s3_class(x, "data.frame")
show_failure(expect_s4_class(x, "data.frame"))
# A data frame is built from a list:
expect_type(x, "list")

# An integer vector is an atomic vector of type "integer"
expect_type(x$x, "integer")
# It is not an S3 object
show_failure(expect_s3_class(x$x, "integer"))

# Above, we requested data.frame() converts strings to factors:
show_failure(expect_type(x$y, "character"))
expect_s3_class(x$y, "factor")
expect_type(x$y, "integer")

testthat

Unit Testing for R

v3.0.2
MIT + file LICENSE
Authors
Hadley Wickham [aut, cre], RStudio [cph, fnd], R Core team [ctb] (Implementation of utils::recover())
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.