Movatterモバイル変換


[0]ホーム

URL:


A brief overview oftinytest

See also theRecordingof my useR2021 talk.

Package setup

A quick way to set things up is as follows.

tinytest::setup_tinytest("pkgdir")

wherepkgdir is a package source directory with a validDESCRIPTION file

The setup is as follows.

  1. Files having names starting withtest are inpkg/inst/tinytest, e.g.test_haha.R. Testfiles are R scripts interspersed with test commands, such asexpect_equal(myfunc(1), 0).
  2. tinytest is added toSuggests: in theDESCRIPTION file.
  3. A file namedtinytest.R is set up inpkg/tests to make sure that tests will be run byR CMD check.

A nice way to set up a completely new package that passesR CMD check is as follows

pkgKitten::kitten("hihi")tinytest::setup_tinytest("hihi")

wherehihi is the name of the new package.

Interactive package testing

Functiondescription
test_all("pkgdir")run all test files (pkg must be loaded).
build_install_test("pkgdir")build, install, and test in temp dir.
run_test_dir("pkgdir")run all test files in a directory (pkg must be loaded).
run_test_file("testfile")run a single test file (pkg must be loaded).

All functions return an object of classtinytests.Results can be printed to screen, summarized withsummaryor converted to data frame withas.data.frame for analyses.The optionverbose (default:2) controlsshowing test progress in the terminal.

Test functions

The syntax of test functions resembles that oftestthat. Forexpectations comparing two results, the first argument represents theobserved value while the second argument represents thedesired value.

Functiondescription
expect_trueArgument must evaluate toTRUE
expect_falseArgument must evaluate toFALSE
expect_equalData and attributes of arguments must be equal
expect_equivalentData of arguments must be equal
expect_identicalTarget and current must beidentical
expect_lengthCheck length of argument
expect_inheritsCurrent object must inherit from the desired class
expect_nullExpression must evaluate toNULL
expect_matchString(s) must match a regular expression.
expect_equal_to_referenceObject must be equal to an object stored on file
expect_equivalent_to_referenceObject must be equivalent to an object stored on file
expect_stdoutExpect a printed message (viaprint orcat)
expect_messageExpression must yield a message
expect_warningExpression must yield a warning
expect_errorExpression must yield an error
expect_silentExpect no errors, no warnings

For tests in a script there is an alternative syntax in the style ofRUnit. For eachfunction of the formexpect_lol there is a function of theformcheckLol.

Monitor side-effects

Side-effects, such as changing environment variables, localesettings, or changing the working directory can cause hard-to-tracebugs. Add the statement

report_side_effects()

to a test file and certain types of side-effects, if any, arereported.

Alternatively, use theside_effects argument to any ofthe test runners, for example

test_all("/path/to/package", side_effects=TRUE)

Run test withcustom environment variables set

Temporarily set environment variables for the run of the test. Forexample:

test_all("/path/to/package", setenv=list("wa_babalooba" = "ba_la_bamboo"))

Print options

Test results (objects of classtinytests) have twoprinting modes: a long format and a short, one-line format. Informationthat is always shown includes:

In long format, the test call and difference between desired andrealized input are shown in full. Global printing options can be setwithoptions(option=value).

Optiondefaultdescription
tt.pr.passesFALSEprint passing tests?
tt.pr.limit10how many results to print?
tt.pr.nlong3how many tests in long format?
tt.pr.colorTRUEprint colored output?

It is also possible to influence these options usingprint.tinytest. Colored output is suppressed on systemswith a"dumb"terminal.

Run tests for an installedpackage

For a package calledhaha that is tested withtinytest, any user that hashaha andtinytest installed can run tests as follows.

tinytest::test_package("haha")

Run tests in parallel

Run tests in parallel over files.

tinytest::test_package("haha", ncpu=3)

Or, for more control:

cl <- parallel::makeCluster(4)parallel::clusterCall(cl, source, "R/functions.R")test_all(cluster=cl)stopCluster(cl)

Use extension packages

Add the following to a test file to use assertions exported byttdo.

using(ttdo)

this will give you excellent diff output of thediffobj package intinytest test results. The high-performancecheckmatepackage also extendstinytest.

Skipping or ignoring tests

Useexit_file() orexit_if_not() to stopexecuting a test file, with an optional message.

exit_file("I'm too tired to test today")exit_if_not(requireNamespace('slartibartfast', quietly=TRUE))

Useignore(testfunction) to run a test but not includethe result in the output.

# both tests run, but only second is recorded.if ( ignore(expect_equal)(1 + 1, 2) ){  expect_true( 1 > 0 )}

Note the placement of brackets.

Useat_home() to detect whether a test is runninginteractively, or viatest_package() (i.e. the wayR CMD check will run it).

if ( at_home() ){  # run tests requiring lots of time.}

The package vignette has some tips on how to use this feature, andhow you can set up your package soR CMD check also runstests protected byat_home() in your environment.

Comparing with data storedon file

Data can be loaded frompkg/inst/tinytest (orsubdirectories). A simple test file might look like this.

desired <- read.csv("mycsvoutput.csv", stringsAsFactors=FALSE)obtained <- compute_my_result()expect_equal(obtained, desired)

If you wish to publish the package on CRAN, make sure that the filesare small enough for the package to be acceptable. See theCRANrepository policy for explicit bounds on package size. Alternativelyyou can avoid installing the data and associated test files by addingthem to.Rinstignore.

More information

See the vignette.

vignette("using_tinytest", package="tinytest")

For the underlying method, see MPJ van der Loo (2021)A Method forDeriving Information from Running R Code The R journal13(1). Or watch theuseR2020 talk onthe paper.


[8]ページ先頭

©2009-2025 Movatter.jp