3

whenをネストされた関数内で使用match.funすると問題が発生します。説明のために、2 つの関数を含む簡単なおもちゃの例 R パッケージを作成しました。後者は単に前者を呼び出します:test_thatmatch.fun

i_dont_throw_error <- function(function_name)
  match.fun(function_name)("hello")

i_throw_error <- function(function_name)
  i_dont_throw_error(function_name)

次にtestthat、次のようにテストを作成しました。

test_that("Testing for an error with match.fun one level deep.",{
  print_function <- function(x)
    print(x)

  expect_equal(i_dont_throw_error("print_function"), "hello")
})

test_that("Testing for an error with match.fun two levels deep.",{
  print_function <- function(x)
    print(x)

  expect_equal(i_throw_error("print_function"), "hello")
})

最初のテストは問題ありませんが、2 番目のテストでエラーが発生します。からの出力testthat

==> devtools::test()

Loading testthatTest
Loading required package: testthat
Testing testthatTest
[1] "hello"
.1
1. Error: Testing for an error with match.fun two levels deep. -----------------
object 'print_function' of mode 'function' was not found
1: withCallingHandlers(eval(code, new_test_environment), error = capture_calls, message = function(c) invokeRestart("muffleMessage"))
2: eval(code, new_test_environment)
3: eval(expr, envir, enclos)
4: expect_equal(i_throw_error("print_function"), "hello") at test_test_me.R:12
5: expect_that(object, equals(expected, label = expected.label, ...), info = info, label = label)
6: condition(object)
7: compare(actual, expected, ...)
8: i_throw_error("print_function")
9: i_dont_throw_error(function_name) at C:\Users\jowhitne\Desktop\eraseMe\testthatTest/R/test_func.R:4
10: match.fun(function_name) at C:\Users\jowhitne\Desktop\eraseMe\testthatTest/R/test_func.R:1
11: get(as.character(FUN), mode = "function", envir = envir)

最初のテストはパスするのに 2 番目のテストが失敗する理由がわかりません。実際、失敗したテストをコンソールから直接実行すると問題なく動作します。

> print_function <- function(x)
+     print(x)
> i_throw_error("print_function") 
[1] "hello"

match.fun環境と関係があることは知っていますが、2 つの環境を検索した後にこれが機能することを期待していました。ここで何が欠けているか分かりますか?助けてくれてありがとう。

4

1 に答える 1