r之在 R 包中测试与用户的交互

pengyingh 阅读:49 2024-09-03 21:39:00 评论:0

我正在开发一个 R 包,其中一个函数通过 readline 通过标准输入实现与用户的交互。 .我现在想知道如何测试这个函数的行为,最好用 testthat图书馆。

好像test_that函数假设答案是 ""用于用户输入。我希望我可以测试用户可能输入的各种答案的行为条件。

下面是一个小的示例代码。在实际开发中,marryme函数在单独的文件中定义并导出到命名空间。devtools::test()在最后一行给我一个错误,因为答案永远不会变成是。我想测试当用户输入 "y" 时函数是否正确返回 true .

library(testthat) 
 
test_that("input", { 
  marryme <- function() { 
    ans <- readline("will you marry me? (y/n) > ") 
    return(ans == "y") 
  } 
 
  expect_false(marryme())  # this is good 
  expect_true(marryme())   # this is no good 
}) 

请您参考如下方法:

将 readLines() 与自定义连接一起使用

通过使用 readLines()而不是 readline() ,您可以定义连接,这允许您使用全局选项对其进行自定义。

您需要执行两个步骤:

  • zzz.R 的包中设置默认选项指向标准输入:
    .onAttach <- function(libname, pkgname){ 
      options(mypkg.connection = stdin()) 
    } 
    
  • 在您的函数中,更改 readlinereadLines(n = 1)并在 readLines() 中设置连接至 getOption("mypkg.connection")

  • 例子

    根据您的 MWE:


        library(testthat) 
     
        options(mypkg.connection = stdin()) 
     
        marryme <- function() { 
          cat("will you marry me? (y/n) > ") 
          ans <- readLines(con = getOption("mypkg.connection"), n = 1) 
          cat("\n") 
          return(ans == "y") 
        } 
     
        test_that("input", { 
     
          f <- file() 
          options(mypkg.connection = f) 
          ans <- paste(c("n", "y"), collapse = "\n") # set this to the number of tests you want to run 
          write(ans, f) 
     
          expect_false(marryme())  # this is good 
          expect_true(marryme())   # this is no good 
          # reset connection 
          options(mypkg.connection = stdin()) 
          # close the file 
          close(f) 
        }) 
    #> will you marry me? (y/n) >  
    #> will you marry me? (y/n) > 
    


    标签:测试
    声明

    1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

    关注我们

    一个IT知识分享的公众号