8

私は R の PKNCA パッケージに取り組んでいます。テスト コードを開発している間、いくつかのテストも良い例になります。それらを両方(テストと例)として保持したい。テストにコピーされる roxygen2 ドキュメント内に何かを埋め込む方法はありますか?

私が考えているのは、次のようなドキュメントです。

#' @exampleTest
#' set.seed(5)
#' rnorm(1) ## -0.8409

そして、それは次のようなテストを生成します:

expect_equal({set.seed(5)
              rnorm(1)}, -0.8409, tol=1e-4)

(tol は、それが数字であり、例に示されている桁数であるという事実から来ています。)

4

2 に答える 2

5

パッケージに関する Hadley Wickham の本のチェックの章でdevtools::run_examples()説明されているように使用します。R CMD CHECK を実行すると、関数の例がテストされます。これは testthat の一部ではなく、標準の R パッケージ チェック システムの一部です。

于 2015-12-04T08:20:13.907 に答える
1

方法はありますが、思ったほどスムーズではありません。testthatブロック内で関数を呼び出す必要があります@examples。関数の例を次に示します。

#' @examples
#'   testStrings <- c("1234567890",
#'                    "123 456 7890")
#'
#'   testthat::expect_equal(extractPhoneNumbers(testStrings), "0123")
extractPhoneNumbers <- function(inputStr) {
    # check input:
    if (!is.character(inputStr)) {
        stop("'inputStr' must be a (vector of) string(s)!")
    }

    # imports
    `%>%` <- stringr::`%>%`
    replace_all <- stringr::str_replace_all
    extract_all <- stringr::str_extract_all

    # intermediary regex's
    visualDelimitersRegex <- "[()+\\-_. ]"
    phoneNumberRegex <- "[:digit:]{10}"

    inputStr %>%
    replace_all(pattern = visualDelimitersRegex, replacement = "") %>%
    extract_all(pattern = phoneNumberRegex)
}

devtools::run_examples()またはを実行するdevtools::checkと、 の呼び出しがエラーをスローするため、両方でエラーがスローされtestthat::expect_equal()ます。

からの出力例はdevtools::check次のようになります

*** SNIP ***
* checking for unstated dependencies in examples ... OK
* checking examples ... ERROR
Running examples in ‘demoPkg-Ex.R’ failed
The error most likely occurred in:

> base::assign(".ptime", proc.time(), pos = "CheckExEnv")
> ### Name: extractPhoneNumbers
> ### Title: Extract Phone Numbers
> ### Aliases: extractPhoneNumbers
> 
> ### ** Examples
> 
>   testStrings <- c("1234567890",
+                    "123 456 7890")
> 
>   testthat::expect_equal(extractPhoneNumbers(testStrings), "0123")
Error: extractPhoneNumbers(testStrings) not equal to "0123"
Modes: list, character
Length mismatch: comparison on first 1 components
Component 1: 1 string mismatch
Execution halted
* checking for unstated dependencies in ‘tests’ ... OK
* checking tests ...
  Running ‘testthat.R’
 OK
* checking PDF version of manual ... OK
* DONE

Status: 1 ERROR
于 2016-01-27T11:52:47.687 に答える