【问题标题】:How to produce jUnit fie with R testthat如何使用 R testthat 生成 jUnit fie
【发布时间】:2018-03-21 04:07:50
【问题描述】:

我有 R 代码(不是包),我想使用 testthat 进行验收测试,并在 Jenkins 中使用输出。

我可以从两个演示代码结构的文件开始:

# -- test.R
source("test-mulitplication.R")

# -- test-mulitplication.R
library(testthat)
test_that("Multipilation works ", {
  res <- 5 * 2
  expect_equal(res, 10)
})

运行后,我想获取一个 xml 文件,其中包含每个测试文件的结果或单个文件中的所有测试。

我注意到 testthat 中有一个reporter 功能,但其中大部分似乎是包内部的。目前尚不清楚如何保存测试结果以及功能的灵活性。

很遗憾,这部分的文档并不完整。

编辑

我现在找到了一种使用更好的语法和 junit 输出选项来测试目录的方法:

# -- tests/accpetance-tests.R
options(testthat.junit.output_file = "test-out.xml")
test_dir("tests/")

# -- tests/test-mulitplication.R
library(testthat)
test_that("Multipilation works ", {
  res <- 5 * 2
  expect_equal(res, 10)
})

我相信这会在报告器内部生成一个 XML 对象,但我仍然不知道如何将它保存到文件中。

我尝试用with_reporter 包装test_dir 调用,但这并没有多大作用。

【问题讨论】:

    标签: r jenkins junit testthat


    【解决方案1】:

    2019 年更新:

    testthat 的 2.1.0 版不再需要 context 才能正常工作。因此,我希望您原始代码中的问题能够正常工作。

    来源:https://www.tidyverse.org/articles/2019/04/testthat-2-1-0/

    原答案:

    testthat commit 4 days ago 引用了此功能。在 testthat 的开发版本中引入了一个新选项。

    如果你运行:

    devtools::install_github("r-lib/testthat")
    options(testthat.output_file = "test-out.xml")
    test_dir("tests/")
    

    这应该会在您的工作目录中生成一个文件。

    问题是它可能不适用于您想要的记者。安装了 testthat 的 devtools 版本:

    options(testthat.output_file = "test-out.xml")
    test_dir("tests/", reporter = "junit")
    

    产生关于 xml2 的错误。尝试 xml2 的 dev 分支并没有解决问题。鉴于此更改是相当新的,它可能值得filing an issue over on github.

    不确定这是否能让您更接近,但我们正在输出一份报告,这是一个开始!

    编辑

    这可行,但您需要确定并在测试顶部添加“上下文”,否则您会收到错误消息。尝试将乘法测试的顶部更改为:

    # -- test-mulitplication.R
    library(testthat)
    context("Testing Succeeded!")
    test_that("Multipilation works ", {
      res <- 5 * 2
      expect_equal(res, 10)
    })
    
    context("Test Failed!")
    test_that("Multipilation works ", {
      res <- 5 * 2
      expect_equal(res, 12)
    })
    

    然后重新运行:

    options(testthat.output_file = "test-out.xml")
    test_dir("tests/", reporter = "junit")
    

    这对我有用!由于某种原因,不包括上下文标头会导致问题。不过,这可能是设计使然。

    【讨论】:

    【解决方案2】:

    test_dir("tests/", reporter = "junit") 的解决方案在结果testthat.Rout 中打印出来。我们可以使用sink() 将其写入其他文件,但这是一种解决方法。

    更好的方法是直接调用JunitReporter对象并指定参数放在哪里报告:

    library(testthat)
    library(packageToTest)
    
    test_check("packageToTest", reporter = JunitReporter$new(file = "junit_result.xml"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 2013-07-09
      • 1970-01-01
      • 2014-09-06
      • 1970-01-01
      • 2013-07-09
      • 2012-09-10
      相关资源
      最近更新 更多