gpt4 book ai didi

r - 在哪里使用 testthat 进行库调用?

转载 作者:行者123 更新时间:2023-11-28 19:45:56 25 4
gpt4 key购买 nike

我正在寻找有关出色的 testthat 的最佳实践帮助。放置您的 library(xyzpackage) 调用以使用所有包功能的最佳位置在哪里?

我首先设置了一个 runtest.R 设置路径和包。然后我运行 test_files(test-code.R),其中 包含上下文和测试。结构示例如下:

# runtests.R
library(testthat)
library(data.table)

source("code/plotdata-fun.R")

mytestreport <- test_file("code/test-plotdata.R")

# does other stuff like append date and log test report (not shown)

在我的测试文件中,例如test-plotdata.R(精简版):

#my tests for plotdata
context("Plot Chart")

test_that("Inputs valid", {

test.dt = data.table(px = c(1,2,3), py = c(1,4,9))
test.notdt <- c(1,2,3)

# illustrating the check for data table as first param in my code
expect_error(PlotMyStandardChart(test.notdt,
plot.me = FALSE),
"Argument must be data table/frame")

# then do other tests with test.dt etc...
})
  1. 这是@hadley 打算使用它的方式吗?从journal article不清楚. 我是否也应该在我的测试文件中复制库调用?您需要在每个上下文中设置一个库,还是只在文件开头设置一个库?

  2. 可以在 中过度调用库(包)吗? ?

  3. 要使用 test_dir() 和其他功能什么是设置文件的最佳方式。我确实在我的函数中使用了 require(),但我也在上下文中设置了测试数据示例。 (在上面的示例中,您会看到我需要 data.table 包供 test.dt 在其他测试中使用)。

感谢您的帮助。

最佳答案

一些建议/意见:

  • 设置每个文件,使其无需额外设置即可使用 test_file 自行运行。如果您只关注较大项目的一小部分(如果运行所有测试很慢,则很有用)
  • 多次调用 library 几乎没有什么损失,因为该函数首先检查包是否已附加
  • 如果您设置每个文件以便它可以与 test_file 一起运行,那么 test_dir 将正常工作而无需执行任何其他操作
  • 您不需要在任何测试文件中使用 library(testthat),因为您可能正在使用 test_filetest_dir 运行它们,这将需要加载 testthat

此外,您可以只看 Hadley 最近的一个包裹,看看他是如何做到的(例如 dplyr tests )。

关于r - 在哪里使用 testthat 进行库调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29556988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com