### Define setup code for test files Source: https://testthat.r-lib.org/news/index.html Use `setup()` to run code at the start of each test file, useful for managing state. ```R setup(code = { ... }) ``` -------------------------------- ### Example of Old Approach with Setup/Teardown Source: https://testthat.r-lib.org/reference/teardown.html Illustrates the older method of using `setup()` and `teardown()` to manage temporary files for testing. This code is intended for demonstration and is wrapped in `if (FALSE)` to prevent execution. ```R if (FALSE) { # \dontrun{ # Old approach tmp <- tempfile() setup(writeLines("some test data", tmp)) teardown(unlink(tmp)) } # } ``` -------------------------------- ### Retrieve path to directory of example tests Source: https://testthat.r-lib.org/reference/testthat_examples.html Use `testthat_examples()` to get the path to the directory containing all example test files. This is useful for listing or iterating over available examples. ```r dir(testthat_examples()) #> [1] "_snaps" "test-failure.R" "test-success.R" ``` -------------------------------- ### Retrieve path to a specific example test file Source: https://testthat.r-lib.org/reference/testthat_examples.html Use `testthat_example(filename)` to get the path to a single example test file. Provide the base name of the file (e.g., "success" for "test-success.R"). ```r testthat_example("success") #> [1] "/home/runner/work/_temp/Library/testthat/examples/test-success.R" ``` -------------------------------- ### Setup and Teardown Functions Source: https://testthat.r-lib.org/reference/teardown.html Demonstrates the usage of `setup()` and `teardown()` functions for managing test resources. Note that this approach is no longer recommended in favor of test fixtures. ```R teardown(code, env = parent.frame()) setup(code, env = parent.frame()) ``` -------------------------------- ### Run Examples in a Package Source: https://testthat.r-lib.org/reference/test_examples.html Use this function to test all examples in a package. The path should point to the directory containing Rd files. Remember that the working directory for tests is 'tests/testthat'. ```r test_examples(path = "../..") ``` -------------------------------- ### Install testthat Development Version Source: https://testthat.r-lib.org/index.html Install the development version of testthat from GitHub using the pak package manager. Ensure pak is installed first. ```r # install.packages("pak") pak::pak("r-lib/testthat") ``` -------------------------------- ### Start test context from a file name Source: https://testthat.r-lib.org/reference/context_start_file.html Use context_start_file to start a test context, specifying the name of the file for context. ```r context_start_file(name) ``` -------------------------------- ### Example of using expect_known_output Source: https://testthat.r-lib.org/reference/expect_known_output.html Demonstrates the first run of expect_known_output, which always succeeds by creating a reference file. Subsequent runs will only succeed if the output remains unchanged. This example uses `print = TRUE` to show the output. ```R tmp <- tempfile() # The first run always succeeds expect_known_output(mtcars[1:10, ], tmp, print = TRUE) #> Warning: `expect_known_output()` was deprecated in the 3rd edition. #> ℹ Please use `expect_snapshot_output()` instead #> Warning: Creating reference output. # Subsequent runs will succeed only if the file is unchanged # This will succeed: expect_known_output(mtcars[1:10, ], tmp, print = TRUE) #> Warning: `expect_known_output()` was deprecated in the 3rd edition. #> ℹ Please use `expect_snapshot_output()` instead if (FALSE) { # \dontrun{ # This will fail expect_known_output(mtcars[1:9, ], tmp, print = TRUE) } # } ``` -------------------------------- ### testthat_examples() and testthat_example() Source: https://testthat.r-lib.org/reference/testthat_examples.html These functions allow users to retrieve paths to built-in example test files. `testthat_examples()` returns the path to the directory containing all example tests, while `testthat_example(filename)` returns the path to a specific test file. ```APIDOC ## Functions for Retrieving Example Test File Paths ### `testthat_examples()` #### Description Retrieves the path to the directory containing all built-in example test files. ### Usage ```R testthat_examples() ``` ### Examples ```R dir(testthat_examples()) #> [1] "_snaps" "test-failure.R" "test-success.R" ``` ### `testthat_example(filename)` #### Description Retrieves the path to a single built-in example test file. ### Usage ```R testthat_example(filename) ``` ### Arguments * `filename` (character) - The name of the test file to retrieve the path for. ### Examples ```R testthat_example("success") #> [1] "/home/runner/work/_temp/Library/testthat/examples/test-success.R" ``` ``` -------------------------------- ### source_test_setup Source: https://testthat.r-lib.org/reference/source_file.html Sources test setup files from a specified path. ```APIDOC ## Function: source_test_setup ### Description Sources test setup files, typically located in the 'tests/testthat' directory. These files are executed before tests run to set up the testing environment. ### Arguments * **path** (string) - Path to the directory containing test setup files. Defaults to "tests/testthat". * **env** (environment) - Environment in which to evaluate the code. Defaults to `test_env()`. ``` -------------------------------- ### Test a Specific Example File Source: https://testthat.r-lib.org/reference/test_examples.html Tests a specific example file by its path. The title defaults to the file path. The working directory for tests is 'tests/testthat'. ```r test_example(path, title = path) ``` -------------------------------- ### Install testthat from CRAN Source: https://testthat.r-lib.org/index.html Install the released version of the testthat package from CRAN using the install.packages function. ```r install.packages("testthat") ``` -------------------------------- ### Basic Expectation Example Source: https://testthat.r-lib.org/articles/custom-expectation.html This is a basic example of how an expectation might be used before defining the custom function. ```R expect_length(mean, 1) ``` -------------------------------- ### test_examples Source: https://testthat.r-lib.org/reference/test_examples.html Tests all examples in Rd files within a specified directory. It treats each example as a single test that passes if the code executes without errors. The default path is '../..'. Remember that the working directory for tests is 'tests/testthat'. ```APIDOC ## test_examples ### Description Tests all examples in Rd files within a specified directory. Each example is treated as a single test that passes if the code executes without errors. This is generally redundant with R CMD check and not recommended for routine practice. ### Usage ```R test_examples(path = "../..") ``` ### Arguments * **path** (string) - Path to the directory containing Rd files. The working directory for tests is `tests/testthat`. ``` -------------------------------- ### Example: Running a test file Source: https://testthat.r-lib.org/reference/test_file.html Demonstrates basic usage of test_file() with a test file path. The output shows the progression of test results, including passes, warnings, and skipped tests. ```r path <- testthat_example("success") test_file(path) #> #> ══ Testing test-success.R ═════════════════════════════════════════════ #> #> [ FAIL 0 | WARN 0 | SKIP 0 | PASS 0 ] #> [ FAIL 0 | WARN 0 | SKIP 0 | PASS 1 ] #> [ FAIL 0 | WARN 0 | SKIP 1 | PASS 1 ] #> [ FAIL 0 | WARN 1 | SKIP 1 | PASS 1 ] #> [ FAIL 0 | WARN 1 | SKIP 1 | PASS 2 ] #> [ FAIL 0 | WARN 1 | SKIP 1 | PASS 3 ] #> [ FAIL 0 | WARN 1 | SKIP 1 | PASS 4 ] #> #> ── Warning (test-success.R:10:3): some tests have warnings ──────────── #> NaNs produced #> Backtrace: #> ▆ #> 1. └─testthat::expect_equal(log(-1), NaN) at test-success.R:10:3 #> 2. └─testthat::quasi_label(enquo(object), label) #> 3. └─rlang::eval_bare(expr, quo_get_env(quo)) #> #> ── Skipped tests (1) ────────────────────────────────────────────────── #> • This test hasn't been written yet (1): test-success.R:6:3 #> #> #> [ FAIL 0 | WARN 1 | SKIP 1 | PASS 4 ] ``` -------------------------------- ### test_example Source: https://testthat.r-lib.org/reference/test_examples.html Tests a single example from an Rd file. It treats the example as one test, succeeding if the code runs without error. The title for the test is derived from the provided path. ```APIDOC ## test_example ### Description Tests a single example from an Rd file. It treats the example as one test, succeeding if the code runs without error. ### Usage ```R test_example(path, title = path) ``` ### Arguments * **path** (string) - Path to a single Rd file. Remember the working directory for tests is `tests/testthat`. * **title** (string) - Test title to use. Defaults to the path. ``` -------------------------------- ### Run tests with default reporter Source: https://testthat.r-lib.org/reference/Reporter.html This example demonstrates running a test file with the default reporter, showing the output including failures, warnings, and skipped tests. ```r path <- testthat_example("success") test_file(path) ``` -------------------------------- ### Example: Expect Less Than Source: https://testthat.r-lib.org/reference/comparison-expectations.html Demonstrates the usage of expect_lt to check if a variable is less than a specified value. The commented-out example shows a failing test case. ```R a <- 9 expect_lt(a, 10) if (FALSE) { # \dontrun{ expect_lt(11, 10) } ``` -------------------------------- ### context_start_file Source: https://testthat.r-lib.org/reference/context_start_file.html Starts a test context from a specified file name. This is useful for organizing tests and is intended for use in external reporters. ```APIDOC ## Function: context_start_file ### Description Starts a test context from a specified file name. This function is intended for use in external reporters to manage test execution contexts. ### Usage ``` context_start_file(name) ``` ### Arguments * **name** (character string) - The name of the file from which to start the context. This argument specifies the test file to be loaded or referenced. ``` -------------------------------- ### Example of local_test_context and reproducible output Source: https://testthat.r-lib.org/reference/local_test_context.html Demonstrates how `local_test_context()` affects output coloring and symbols within a local environment. The example shows that text will not be colored and uses the ellipsis symbol. ```r local({ local_test_context() cat(cli::col_blue("Text will not be colored")) cat(cli::symbol$ellipsis) cat("\n") }) ``` -------------------------------- ### Example: Using a different reporter Source: https://testthat.r-lib.org/reference/test_file.html Shows how to specify a different reporter, 'minimal' in this case, to change the output format of the test results. ```r test_file(path, reporter = "minimal") #> .SW... ``` -------------------------------- ### Setup and Teardown with Options Source: https://testthat.r-lib.org/articles/special-files.html Demonstrates how to temporarily modify R options for testing and ensure they are reset afterwards using withr::defer. This is useful for disabling interactive features during tests. ```R op <- options(reprex.clipboard = FALSE, reprex.html_preview = FALSE) withr::defer(options(op), teardown_env()) ``` -------------------------------- ### Skip if Package Not Installed Source: https://testthat.r-lib.org/articles/skipping.html Use this helper to skip tests if a required package is not installed. Optionally specify a minimum version. ```R library(testthat) ``` -------------------------------- ### Skip test if package not installed with minimum version Source: https://testthat.r-lib.org/news/index.html Use `skip_if_not_installed()` with the `minimum_version` argument to skip tests if a package is not installed or is an older version. ```R skip_if_not_installed("some_package", minimum_version = "1.0.0") ``` -------------------------------- ### expect_silent with a function producing output Source: https://testthat.r-lib.org/reference/expect_silent.html This example demonstrates how expect_silent fails when the code within it produces output (message, warning, or print). The example is wrapped in `if (FALSE)` to prevent it from running during package checks, as it's designed to show a failure case. ```r f <- function() { message("Hi!") warning("Hey!!") print("OY!!!") } if (FALSE) { # \dontrun{ expect_silent(f()) } # } ``` -------------------------------- ### Example Usage of describe Source: https://testthat.r-lib.org/reference/describe.html Demonstrates how to use `describe` and `it` to write tests for a function, including nested describe blocks and handling of unimplemented tests. ```APIDOC ## Example 1: Basic Usage __``` describe("matrix()", { it("can be multiplied by a scalar", { m1 <- matrix(1:4, 2, 2) m2 <- m1 * 2 expect_equal(matrix(1:4 * 2, 2, 2), m2) }) it("can have not yet tested specs") }) #> ── Skip: matrix() / can have not yet tested specs ───────────────────── #> Reason: empty test #> Test passed with 1 success 🥳. ``` ## Example 2: Nested describe blocks __``` addition <- function(a, b) a + b division <- function(a, b) a / b describe("math library", { describe("addition()", { it("can add two numbers", { expect_equal(1 + 1, addition(1, 1)) }) }) describe("division()", { it("can divide two numbers", { expect_equal(10 / 2, division(10, 2)) }) it("can handle division by 0") #not yet implemented }) }) #> ── Skip: math library / division() / can handle division by 0 ───────── #> Reason: empty test #> Test passed with 2 successes 😀. ``` ``` -------------------------------- ### Initialize Teardown Environment Source: https://testthat.r-lib.org/reference/teardown_env.html Use this function in setup files to create an environment for deferred cleanup operations. It's intended to be used with withr::defer() to ensure code runs after all tests. ```r teardown_env() ``` -------------------------------- ### Configuring load_all arguments for package tests Source: https://testthat.r-lib.org/reference/test_dir.html This example shows how to specify arguments for pkgload::load_all() within the DESCRIPTION file when using the 'source' option for load_package in test_dir. This allows customization of how the package is loaded during testing. ```R Config/testthat/load-all: list(export_all = FALSE, helpers = FALSE) ``` -------------------------------- ### Mock requireNamespace for package installation checks Source: https://testthat.r-lib.org/articles/mocking.html Uses local_mocked_bindings to mock the requireNamespace function. The first mock always returns TRUE, and the second always returns FALSE, allowing for isolated testing of package installation checks. ```r test_that("check_installed() checks package is installed", { local_mocked_bindings(requireNamespace = function(...) TRUE) expect_no_error(check_installed("package-name")) local_mocked_bindings(requireNamespace = function(...) FALSE) expect_snapshot(check_installed("package-name"), error = TRUE) }) ``` -------------------------------- ### Setup and Teardown for Package-Wide Tests Source: https://testthat.r-lib.org/articles/test-fixtures.html This R code demonstrates how to set up external resources before any tests run and clean them up afterward using `withr::defer` within a `tests/testthat/setup.R` file. It writes a CSV file and ensures its deletion after all tests complete. ```r # Run before any test write.csv(mtcars, "mtcars.csv") # Run after all tests withr::defer(unlink("mtcars.csv"), teardown_env()) ``` -------------------------------- ### Basic Quasi-labelling Example Source: https://testthat.r-lib.org/reference/quasi_label.html Demonstrates how to use unquoting (!!) with expect_equal to improve failure messages. This is useful when the expression being tested involves variables whose values are important for debugging. ```R f <- function(i) if (i > 3) i * 9 else i * 10 i <- 10 # This sort of expression commonly occurs inside a for loop or function # And the failure isn't helpful because you can't see the value of i # that caused the problem: show_failure(expect_equal(f(i), i * 10)) #> Failed expectation: #> Expected `f(i)` to equal `i * 10`. #> Differences: #> `actual`: 90.0 #> `expected`: 100.0 # # To overcome this issue, testthat allows you to unquote expressions using # !!. This causes the failure message to show the value rather than the # variable name show_failure(expect_equal(f(!!i), !!(i * 10))) #> Failed expectation: #> Expected `f(10)` to equal 100. #> Differences: #> `actual`: 90.0 #> `expected`: 100.0 # ``` -------------------------------- ### Recommended Test Fixture Approach Source: https://testthat.r-lib.org/reference/teardown.html Presents the currently recommended approach using a local function to manage test data and ensure cleanup via `withr::defer`. This is a more robust and modern alternative to `setup()` and `teardown()`. ```R local_test_data <- function(env = parent.frame()) { tmp <- tempfile() writeLines("some test data", tmp) withr::defer(unlink(tmp), env) tmp } # Then call local_test_data() in your tests ``` -------------------------------- ### Using expect_that with is_identical_to Source: https://testthat.r-lib.org/reference/expect_that.html Shows how to use `expect_that` with `is_identical_to` for exact value comparison. This example is wrapped in a conditional block to prevent execution. ```R if (FALSE) { # \dontrun{ expect_that(sqrt(2) ^ 2, is_identical_to(2)) } # } ``` -------------------------------- ### Basic Skip Example Source: https://testthat.r-lib.org/reference/skip.html Demonstrates how to use `skip()` to skip a test. The test will be marked as skipped, and subsequent expectations within the same `test_that` block will not be executed. ```R if (FALSE) skip("Some Important Requirement is not available") ``` ```R test_that("skip example", { expect_equal(1, 1L) # this expectation runs skip('skip') expect_equal(1, 2) # this one skipped expect_equal(1, 3) # this one is also skipped }) ``` -------------------------------- ### Specify Tests to Start First in DESCRIPTION Source: https://testthat.r-lib.org/articles/parallel.html Define a comma-separated list of glob patterns in the Config/testthat/start-first field of your DESCRIPTION file to prioritize the execution of specific slow tests. This can improve overall test performance. ```R Config/testthat/start-first: watcher, parallel* ``` -------------------------------- ### Run tests with a specific reporter Source: https://testthat.r-lib.org/reference/Reporter.html This example shows how to override the default reporter by specifying a different reporter, such as "minimal", when running a test file. ```r # Override the default by supplying the name of a reporter test_file(path, reporter = "minimal") ``` -------------------------------- ### test_file Function Source: https://testthat.r-lib.org/reference/test_file.html Runs all tests in a single file. Helper, setup, and teardown files located in the same directory as the test will also be run. ```APIDOC ## test_file(path, reporter = default_compact_reporter(), desc = NULL, package = NULL, shuffle = FALSE, ...) ### Description Runs all tests in a single file. Helper, setup, and teardown files located in the same directory as the test will also be run. ### Arguments * **path** (string) - Path to file. * **reporter** (string or R6 object) - Reporter to use to summarise output. Can be supplied as a string (e.g. "summary") or as an R6 object (e.g. `SummaryReporter$new()`). See Reporter for more details and a list of built-in reporters. * **desc** (string) - Optionally, supply a string here to run only a single test (`test_that()` or `describe()`) with this `desc`ription. * **package** (string) - If these tests belong to a package, the name of the package. * **shuffle** (boolean) - If `TRUE`, randomly reorder the top-level expressions in the file. * **...** - Additional parameters passed on to `test_dir()` ### Value A list (invisibly) containing data about the test results. ### Environments Each test is run in a clean environment to keep tests as isolated as possible. For package tests, that environment inherits from the package's namespace environment, so that tests can access internal functions and objects. ### Examples ```R path <- testthat_example("success") test_file(path) test_file(path, desc = "some tests have warnings") test_file(path, reporter = "minimal") ``` ``` -------------------------------- ### Nested Describe Blocks for Math Functions Source: https://testthat.r-lib.org/reference/describe.html Demonstrates nested describe blocks to organize tests for different functions within a library. Includes examples of implemented and not-yet-implemented specifications. ```R addition <- function(a, b) a + b division <- function(a, b) a / b describe("math library", { describe("addition()", { it("can add two numbers", { expect_equal(1 + 1, addition(1, 1)) }) }) describe("division()", { it("can divide two numbers", { expect_equal(10 / 2, division(10, 2)) }) it("can handle division by 0") #not yet implemented }) }) ``` -------------------------------- ### Base R implementation of check_installed Source: https://testthat.r-lib.org/articles/mocking.html A simple R function to check if a package is installed and optionally enforce a minimum version. ```r check_installed <- function(pkg, min_version = NULL) { if (!requireNamespace(pkg, quietly = TRUE)) { stop(sprintf("{%s} is not installed.", pkg)) } if (!is.null(min_version)) { pkg_version <- packageVersion(pkg) if (pkg_version < min_version) { stop(sprintf( "{%s} version %s is installed, but %s is required.", pkg, pkg_version, min_version )) } } invisible() } ``` -------------------------------- ### Snapshotting a PNG Image Source: https://testthat.r-lib.org/reference/expect_snapshot_file.html This example demonstrates how to snapshot a PNG image generated by R's plotting functions. It uses a helper function `save_png` to create the image file and then `expect_snapshot_file` to compare it against a reference. ```R save_png <- function(code, width = 400, height = 400) { path <- tempfile(fileext = ".png") png(path, width = width, height = height) on.exit(dev.off()) code path } path <- save_png(plot(1:5)) path #> [1] "/tmp/Rtmpt68oXv/file1bfa26b38a43.png" if (FALSE) { # \dontrun{ expect_snapshot_file(save_png(hist(mtcars$mpg)), "plot.png") } # } ``` -------------------------------- ### Setup R CMD check test script Source: https://testthat.r-lib.org/reference/test_package.html Create a `tests/testthat.R` file to run testthat tests automatically during `R CMD check`. This script loads necessary libraries and calls `test_check()`. ```R library(testthat) library(yourpackage) test_check("yourpackage") ``` -------------------------------- ### Run tests in a single file Source: https://testthat.r-lib.org/reference/test_file.html Use test_file() to run all tests within a specified R file. Helper, setup, and teardown files in the same directory are also executed. ```r test_file( path, reporter = default_compact_reporter(), desc = NULL, package = NULL, shuffle = FALSE, ... ) ``` -------------------------------- ### Recycling mock sequence outputs Source: https://testthat.r-lib.org/reference/mock_output_sequence.html This example shows how to use `mock_output_sequence` with `recycle = TRUE` to repeatedly cycle through a sequence of mock return values. This is useful when a mocked function is expected to be called more times than there are unique values to return. ```R recycled_mocked_sequence <- mock_output_sequence( "3", "This is a note", "n", recycle = TRUE ) recycled_mocked_sequence() #> [1] "3" recycled_mocked_sequence() #> [1] "This is a note" recycled_mocked_sequence() #> [1] "n" recycled_mocked_sequence() #> [1] "3" ``` -------------------------------- ### Example C++ Unit Test with Catch and testthat Source: https://testthat.r-lib.org/reference/use_catch.html This snippet demonstrates a basic C++ unit test using Catch's `context` and `test_that` wrappers, along with `expect_true` for assertion. Ensure Catch and testthat are linked correctly. ```C++ context("C++ Unit Test") { test_that("two plus two is four") { int result = 2 + 2; expect_true(result == 4); } } ``` -------------------------------- ### Executing Deferred Events in Global Environment Source: https://testthat.r-lib.org/articles/test-fixtures.html This R example shows how to manually execute deferred cleanup actions set by withr::defer() in the global environment using deferred_run(). This is necessary because the global environment is not automatically cleaned up. ```R withr::defer(print("hi")) #> Setting deferred event(s) on global environment. #> * Execute (and clear) with `deferred_run()`. #> * Clear (without executing) with `deferred_clear()`. withr::deferred_run() #> [1] "hi" ``` -------------------------------- ### local_mocked_bindings and with_mocked_bindings Source: https://testthat.r-lib.org/reference/local_mocked_bindings.html `with_mocked_bindings()` and `local_mocked_bindings()` provide tools for "mocking", temporarily redefining a function so that it behaves differently during tests. This is helpful for testing functions that depend on external state (i.e. reading a value from a file or a website, or pretending a package is or isn't installed). ```APIDOC ## Usage __``` local_mocked_bindings(..., .package = NULL, .env = caller_env()) with_mocked_bindings(code, ..., .package = NULL) ``` ## Arguments ... Name-value pairs providing new values (typically functions) to temporarily replace the named bindings. .package The name of the package where mocked functions should be inserted. Generally, you should not supply this as it will be automatically detected when whole package tests are run or when there's one package under active development (i.e. loaded with `pkgload::load_all()`). We don't recommend using this to mock functions in other packages, as you should not modify namespaces that you don't own. .env Environment that defines effect scope. For expert use only. code Code to execute with specified bindings. ``` -------------------------------- ### Test check_installed for package installation Source: https://testthat.r-lib.org/articles/mocking.html Tests that check_installed correctly identifies if a package is installed or not. It relies on external state for package availability. ```r test_that("check_installed() checks package is installed", { expect_no_error(check_installed("testthat")) expect_snapshot(check_installed("doesntexist"), error = TRUE) }) ``` -------------------------------- ### Run tests for an installed package Source: https://testthat.r-lib.org/reference/test_package.html Use `test_package()` to run tests for an installed R package by its name. It accepts a reporter argument to customize output. ```R test_package("yourpackage") ``` -------------------------------- ### Skipping Based on Package Installation with skip_if_not_installed() Source: https://testthat.r-lib.org/reference/skip.html Skips a test if a specified package is not installed or cannot be loaded. This is useful for tests that depend on optional or suggested packages. ```APIDOC ## skip_if_not_installed() ### Description Skips tests if a specified package is not installed or cannot be loaded using `requireNamespace()`. ### Usage ```R skip_if_not_installed(pkg, minimum_version = NULL) ``` ### Arguments * `pkg` (string) - The name of the package to check for. * `minimum_version` (string, optional) - The minimum required version for the package. ``` -------------------------------- ### Example: Expect Greater Than Source: https://testthat.r-lib.org/reference/comparison-expectations.html Demonstrates the usage of expect_gt to check if a variable is greater than a specified value. The commented-out example shows a failing test case. ```R a <- 11 expect_gt(a, 10) if (FALSE) { # \dontrun{ expect_gt(9, 10) } ``` -------------------------------- ### Combined Expectations Example Source: https://testthat.r-lib.org/articles/custom-expectation.html This example demonstrates combining multiple checks into a single custom expectation. Note that failures in combined expectations can lead to multiple failure messages. ```R # from tidytext expect_nrow <- function(tbl, n) { expect_s3_class(tbl, "data.frame") expect_equal(nrow(tbl), n) } ``` -------------------------------- ### Example of a failing test (commented out) Source: https://testthat.r-lib.org/reference/test_that.html This example demonstrates how a test might be written to intentionally fail, useful for testing error handling or specific conditions. It is commented out with \dontrun{} to prevent execution. ```R if (FALSE) { # \dontrun{ test_that("trigonometric functions match identities", { expect_equal(sin(pi / 4), 1) }) } # } ``` -------------------------------- ### Basic Usage of expect_invisible and expect_visible Source: https://testthat.r-lib.org/reference/expect_invisible.html Demonstrates the fundamental usage of expect_invisible to check for invisible output and expect_visible to check for visible output. ```R expect_invisible(x <- 10) expect_visible(x) ``` -------------------------------- ### Basic Usage of expect_true and expect_false Source: https://testthat.r-lib.org/reference/logical-expectations.html Demonstrates the fundamental usage of expect_true and expect_false. Use these when you need to assert that a condition evaluates to TRUE or FALSE. ```R expect_true(2 == 2) # Failed expectations will throw an error show_failure(expect_true(2 != 2)) ``` -------------------------------- ### Prepare to mock base R functions Source: https://testthat.r-lib.org/articles/mocking.html Creates null bindings for base R functions requireNamespace and packageVersion in the current environment, preparing them to be mocked. ```r requireNamespace <- NULL packageVersion <- NULL ``` -------------------------------- ### Mocking system_os() to test skip_on_os() Source: https://testthat.r-lib.org/articles/mocking.html Use `local_mocked_bindings()` to mock `system_os()` and simulate running on a specific operating system. This is useful for testing functions like `skip_on_os()` that behave differently across platforms. ```R test_that("can skip on multiple oses", { local_mocked_bindings(system_os = function() "windows") expect_skip(skip_on_os("windows")) expect_skip(skip_on_os(c("windows", "linux"))) expect_no_skip(skip_on_os("linux")) }) ``` -------------------------------- ### LocationReporter Example Source: https://testthat.r-lib.org/reference/LocationReporter.html This reporter prints the location of every expectation and error. Useful for debugging segfaults or C/C++ breakpoints. ```R reporter("location") ``` -------------------------------- ### Get Default Reporter for test_package() Source: https://testthat.r-lib.org/reference/default_reporter.html Returns the default reporter for `test_package()`. It defaults to `CheckReporter`, which can be overridden with the `testthat.default_check_reporter` option. ```R check_reporter() ``` -------------------------------- ### Demonstrating mock_output_sequence behavior Source: https://testthat.r-lib.org/reference/mock_output_sequence.html This snippet demonstrates the sequential return values of a mock created by `mock_output_sequence`. It shows the output for each call and the error that occurs when the sequence is exhausted without recycling. ```R # for understanding mocked_sequence <- mock_output_sequence("3", "This is a note", "n") mocked_sequence() #> [1] "3" mocked_sequence() #> [1] "This is a note" mocked_sequence() #> [1] "n" try(mocked_sequence()) #> Error in mocked_sequence() : Can't find value for 4th iteration. #> ℹ `...` has only 3 values. #> ℹ You can set `recycle` to `TRUE`. ``` -------------------------------- ### Skip test if condition is true Source: https://testthat.r-lib.org/news/index.html Use `skip_if()` to conditionally skip a test. For example, skip tests in older R versions. ```R skip_if(getRversion() <= 3.1) ``` -------------------------------- ### Using mock_output_sequence() for Input Sequences Source: https://testthat.r-lib.org/articles/challenging-tests.html Demonstrates the use of `mock_output_sequence()` to create a function that returns a predefined sequence of values on successive calls. This is useful for testing functions that consume input iteratively. ```R f <- mock_output_sequence(1, 12, 123) f() #> [1] 1 f() #> [1] 12 f() #> [1] 123 ``` -------------------------------- ### Basic unix_time function Source: https://testthat.r-lib.org/articles/mocking.html A simple function to get the current Unix time. This serves as a basis for demonstrating time manipulation through mocking. ```R unix_time <- function() unclass(Sys.time()) unix_time() #> [1] 1768230020 ```