2

我需要测试包加载操作(对于我的多版本包)并且知道卸载命名空间和东西是危险的工作。所以我想在一个新的 R 会话中运行每个测试。并行运行我的测试不能满足这个需求,因为它会重用从站,并且这些会变脏。

所以我想callr::r会帮助我。不幸的是,我再次被记录在案的记者所困。

以下是一个最小的示例。放在文件中test-mytest.R

test_that('test 1', {
    expect_equal(2+2, 5)
})

reporter_in <- testthat::get_reporter()

# -- 1 --

reporter_out <- callr::r(

    function(reporter) {
        
        reporter <- testthat::with_reporter(reporter, {

           testthat::test_that("test inside", {
              testthat::expect_equal('this', 'wont match')
           })
       })
    },
    args = list(reporter = reporter_in),
    show = TRUE
)

# -- 2 --
testthat::set_reporter(reporter_out)

# -- 3 --
test_that('test 2', {
    expect_equal(2+2, 8)
})

我使用以下方法调用了这个测试文件:

# to be able to check the outcome, work with a specific reporter
summary <- testthat::SummaryReporter$new()
testthat::test_file('./tests/testthat/test-mytest.R', reporter = summary)

这似乎可以满足我的要求,但是在查看结果时...

> summary$end_reporter()

== Failed ===============================================================================================
-- 1. Failure (test-load_b_pick_last_true.R:5:5): test 1 ------------------------------------------------
2 + 2 (`actual`) not equal to 5 (`expected`).

  `actual`: 4
`expected`: 5

== DONE =================================================================================================

...这只是返回的第一个测试。

这个怎么运作:

  • 执行普通测试。
  • 获取当前使用的记者(-- 1 --
  • callr::r用于调用包含测试的测试块。
  • 在通话中,我尝试使用set_reporter,但with_reporter实际上是相同的。
  • 呼叫返回记者(用callr::r尝试过get_reporter(),但with_reporter也返回记者(隐形))

现在返回的记者似乎很好,但是当将其设置为实际的记者时set_reporter,似乎并没有覆盖实际的记者。

请注意,在 处-- 2 --reporter_out包含两个测试结果。

问题

我不确定我希望它做什么,但最后我希望将结果添加到原始报告器((summary或)reporter_in,也就是说,如果那不是某种副本)。

4

1 回答 1

0

我能想到的一种解决方法是将实际的测试执行移到callr::r调用之外,但在里面收集测试用例。我认为它很简洁,只要您可以将这些辅助函数(请参阅详细示例)放在您的包中,您就可以编写测试,而且开销很小。

虽然它没有回答如何使用“记者”对象......

简单的例子:

test_outcome <- callr::r(
    function() {
        # devtools::load_all()
        list(
           check1 = mypackage::sum(5,5),  # some imaginary exported functions sum and name.
           check2 = mypackage::name()
        )
    }
)
test_that('My test case', {
    expect_equal(test_outcome$check1, 10)
    expect_equal(test_outcome$check2, 'Siete')
})

详细示例

请注意, from .add_testto.exp_true只是可以更好地包含在包中的函数定义,因此它们在加载时可用devtools::load_all(). load_all默认情况下还加载未导出的函数。

test_outcome <- callr::r(
    function() {
        # devtools::load_all()

        # Defining helper functions
        tst <- list(desc = 'My first test', tests = list())

        .add_test <- function(type, A, B) {
            # To show at least something about what is actually tested when returning the result, we can add the actual `.exp_...` call to the test.
            call <- as.character(sys.call(-1))

            tst$tests[[length(tst$tests) + 1]] <<- list(
                type = type, a = A, b = B,
                # (I couldn't find a better way to create a nice call string)
                call = paste0(call[1], '(', paste0(collapse = ', ', call[2:length(call)]), ')'))
        }
        .exp_error <- function(expr, exp_msg) {
            err_msg <- ''
            tryCatch({expr}, error = function(err) {
                err_msg <<- err$message
            })
            .add_test('error', err_msg, exp_msg)
        }
        .exp_match <- function(expr, regex) {
            .add_test('match', expr, regex)
        }
        .exp_equal <- function(expr, ref) {
            .add_test('equal', expr, ref)
        }
        .exp_false <- function(expr) {
            .add_test('false', expr, FALSE)
        }
        .exp_true <- function(expr) {
            .add_test('true', expr, TRUE)
        }

        # Performing the tests
        .exp_match('My name is Siete', 'My name is .*')
        .exp_equal(mypackage::sum(5,5), 10)  # some imaginary exported functions sum and name.
        .exp_match(mypackage::name(), 'Siete')
    
        .exp_false('package:testthat' %in% search())

        return(tst)
    },
    show = TRUE)

# Performing the actual testthat tests:
.run_test_batch <- function(test_outcome) {
    test_that(test_outcome$desc, {
        for (test in test_outcome$tests) {

            # 'test' is a list with the fields 'type', 'a', 'b' and 'call'.
            # Where 'type' can contain 'match', 'error', 'true', 'false' or 'equal'.
            if (test$type == 'equal') {
                with(test, expect_equal(a, b, label = call))

            } else if (test$type == 'true') {
                expect_true( test$a, label = test$call)

            } else if (test$type == 'false') {
                expect_false(test$a, label = test$call)

            } else if (test$type %in% c('match', 'error')) {
                with(test, expect_match(a, b, label = call))
            }
        }
    })
}

.run_test_batch(test_outcome)

将函数移动到包中时,您还需要以下初始化函数。

tst <- new.env(parent = emptyenv())
tst$desc = ''
tst$tests = list()

.initialize_test <- function(desc) {
    tst$desc = desc
    tst$tests = list()
}

它的工作原理如下:

  • 创建一个空列表:tst
  • 通过调用.exp_...函数,测试被添加到该列表中
  • 包含测试的列表由函数返回callr::r
  • 然后我们遍历列表并执行每个测试
于 2021-12-30T16:28:36.790 回答