【问题标题】:testthat in R: sourcing in tested filesR中的testthat:在测试文件中采购
【发布时间】:2014-09-09 11:51:48
【问题描述】:

我在 R 中使用 testthat 包,我正在尝试测试一个函数 在文件example.R 中定义。该文件包含一个调用source("../utilities/utilities.R"),其中utilities.R 是一个包含我编写的函数的文件。但是,当我尝试从 example.R 测试函数时,在测试脚本中获取它会出现以下错误:

Error in file(filename, "r", encoding = encoding) : 
  cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file '../utilities/utilities.R': No such file or directory

您能否说明如何对来自另一个文件的文件中的函数运行测试?

【问题讨论】:

  • 你试过把这个文件放在同一个文件夹里吗?
  • 将文件放入同一目录并将其作为source("utilities.R") in example.R 提供无济于事:我收到类似的错误消息。

标签: r testthat


【解决方案1】:

可能有点晚了,但我找到了解决方案。 Test_that 将保存测试文件的目录设置为当前工作目录。请参阅 test-files.r 中的以下代码。这会导致工作目录为 /tests。因此,您的主要脚本需要 source ("../file.R"),它适用于测试,但不适用于运行您的应用程序。

https://github.com/hadley/testthat/blob/master/R/test-files.r

source_dir <- function(path, pattern = "\\.[rR]$", env = test_env(),
                       chdir = TRUE) {
  files <- normalizePath(sort(dir(path, pattern, full.names = TRUE)))
  if (chdir) {
    old <- setwd(path)
    on.exit(setwd(old))
  }

我找到的解决方案是在我的测试文件中添加 setwd("..") 并简单地获取不带路径的文件名。源(“file.R”)而不是源(“../file.R”)。似乎对我有用。

【讨论】:

  • 由于我的测试、数据和函数都在不同的文件夹中,我发现我需要将工作目录分配为 wd
【解决方案2】:

testthat 允许您定义和获取帮助文件(请参阅?source_test_helpers):

Helper 脚本是伴随测试脚本的 R 脚本,但前缀为 helper。这些脚本在测试运行之前运行一次。

所以对我来说完美的工作就是简单地将一个文件“helper-functions.R”包含我想要在“/tests/testthat/”中获取的代码。您不必自己调用source_test_helpers(),testthat 会在您运行测试时自动调用(例如,通过devtools::test()testthat::test_dir())。

【讨论】:

    【解决方案3】:

    我发现这个问题没有很好的解决方案,到目前为止,我一直是使用包here 在每个测试中设置工作目录。

    test_that('working directory is set',{
      setwd(here())
      # test code here
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-15
      • 1970-01-01
      • 2015-10-11
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2014-08-19
      相关资源
      最近更新 更多