Learn R Programming

testthat (version 3.2.1)

equality-expectations: Does code return the expected value?

Description

These functions provide two levels of strictness when comparing a computation to a reference value. expect_identical() is the baseline; expect_equal() relaxes the test to ignore small numeric differences.

In the 2nd edition, expect_identical() uses identical() and expect_equal uses all.equal(). In the 3rd edition, both functions use waldo. They differ only in that expect_equal() sets tolerance = testthat_tolerance() so that small floating point differences are ignored; this also implies that (e.g.) 1 and 1L are treated as equal.

Usage

expect_equal(
  object,
  expected,
  ...,
  tolerance = if (edition_get() >= 3) testthat_tolerance(),
  info = NULL,
  label = NULL,
  expected.label = NULL
)

expect_identical( object, expected, info = NULL, label = NULL, expected.label = NULL, ... )

Arguments

object, expected

Computation and value to compare it to.

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

...

3e: passed on to waldo::compare(). See its docs to see other ways to control comparison.

2e: passed on to compare()/identical().

tolerance

3e: passed on to waldo::compare(). If non-NULL, will ignore small floating point differences. It uses same algorithm as all.equal() so the tolerance is usually relative (i.e. mean(abs(x - y) / mean(abs(y)) < tolerance), except when the differences are very small, when it becomes absolute (i.e. mean(abs(x - y) < tolerance). See waldo documentation for more details.

2e: passed on to compare(), if set. It's hard to reason about exactly what tolerance means because depending on the precise code path it could be either an absolute or relative tolerance.

info

Extra information to be included in the message. This argument is soft-deprecated and should not be used in new code. Instead see alternatives in quasi_label.

label, expected.label

Used to customise failure messages. For expert use only.

See Also

  • expect_setequal()/expect_mapequal() to test for set equality.

  • expect_reference() to test if two names point to same memory address.

Other expectations: comparison-expectations, expect_error(), expect_length(), expect_match(), expect_named(), expect_null(), expect_output(), expect_reference(), expect_silent(), inheritance-expectations, logical-expectations

Examples

Run this code
a <- 10
expect_equal(a, 10)

# Use expect_equal() when testing for numeric equality
if (FALSE) {
expect_identical(sqrt(2) ^ 2, 2)
}
expect_equal(sqrt(2) ^ 2, 2)

Run the code above in your browser using DataLab