Skip to content
This repository has been archived by the owner on Jun 30, 2023. It is now read-only.

Guide for writing tests

Chung-hong Chan edited this page Feb 5, 2022 · 1 revision

This is a quick guide for writing tests for this package.

From this point onward, this package uses a new format for unit tests. If you want to contribute to this package with new functions, you need to write some unit tests. For a general introduction on how to write unit tests, please consult the section on test in this book.

This is a package of an API client. It is tricky to test and the way this package made testing work is to use httptest. The general idea is to cache the responses from the API and store them inside this directory (tests/testthat/api.twitter.com/2). When tests are running, R doesn't need to make calls to the API. Instead, it unpacks the recorded responses from the aforementioned directory. As most of the responses need the HTTP header also for the Twitter API, you need to use start_capturing(simplify = FALSE). This technique is called "mock API".

However, this kind of tests occupies a lot of disk space and it can easily exceed the 5MB rule of CRAN. These tests need to be skipped in the CRAN check. We did that by ignore the aforementioned directory in .Rbuildignore. However, we'd want these tests to be run in the CI (Github Actions in this case) and the local machine. In order to achieve this delicacy, the unit test must be written in a specific format.

The following is an example of a unit test.

## require(httptest)
## start_capturing(simplify = FALSE)
## get_all_tweets(query = "#commtwitter", start_tweets = "2021-06-01T00:00:00Z", end_tweets = "2021-06-05T00:00:00Z", data_path = "../testdata/commtwitter")
## stop_capturing()


with_mock_api({
  test_that("params: default", {
    skip_if(!dir.exists("api.twitter.com"))
    emptydir <- academictwitteR:::.gen_random_dir()
    ## "Normal" usage; at least the default
    expect_error(w0 <- capture_warnings(get_all_tweets(query = "#commtwitter", start_tweets = "2021-06-01T00:00:00Z", end_tweets = "2021-06-05T00:00:00Z")), NA)
    unlink(emptydir, recursive = TRUE)
  })
})

please follow the following conventions

  1. Please keep the code capturing recorded responses as comment in the test file.
  2. For tests involving the mock API, please use the directive skip_if(!dir.exists("api.twitter.com")) to skip the test. For other tests that require other prerequisites (e.g. a specific RDS file, envvars such as TWITTER_BEARER), you should use the same skip_if to skip the test. For more examples, please see this file.
  3. You don't need to put the test file in the .Rbuildignore
Clone this wiki locally