Skip all testthat tests when the condition is not met

What is the correct way to skip all tests in the test directory of package R when using the testthat / devtools framework? For example, if there is no connection to the database, and all the tests rely on this connection, do I need to write skip in all files separately or write one skip somewhere?

I have a standard package setting that looks like

MyPackage /

  • ... # another package.
  • Tests /
    • testthat.R
    • testthat /
      • test thing1.R
      • test thing2.R

At first it seemed to me that I could put the test in the testthat.R file, for example

 ## in testthat.R library(testthat) library(mypackage) fail_test <- function() FALSE if (fail_test()) test_check("package") 

but this did not work, and it seems that the call to devtools::test() simply ignores this file. I guess the alternative would be to keep all the tests in a different directory, but is there a better solution?

+5
source share
2 answers

The Skip Test section of R Packages covers this use case. Essentially, you are writing a custom function that checks all the conditions that you need to check - regardless of whether you can connect to your database - and then call this function from all tests that require this condition to be met.

Example calculated from the book:

 skip_if_no_db <- function() { if (db_conn()) { skip("API not available") } } test_that("foo api returns bar when given baz", { skip_if_no_db() ... }) 

I found this approach more useful than a single switch to disable all tests, since I usually combine a test that does and does not rely on all the conditions that I check, and I want to always run as many tests as possible.

+1
source

Perhaps you can organize the tests in subdirectories by inserting the conditional inclusion of the directory into the test of the parent folder:

Consider the β€œtests” in the testthat package. In particular, it looks interesting:

I do not see anything here that repeats subdirectories in the test scan:

0
source

Source: https://habr.com/ru/post/1240223/


All Articles